Скручивание страницы слева направо Android

Итак, я использую скручивание страницы с помощью harism, https://github.com/harism/android_page_curl и успешно реализовал его для загрузки изображения через веб-поток. Но не могу заставить его работать, когда я возвращаюсь к предыдущим изображениям или страницам, поскольку изображения не имеют правильного индекса. то есть они не обновляются должным образом. Я не могу понять это.

Это моя реализация, в которой я загружаю изображения в PageProvider

private class PageProvider implements CurlView.PageProvider {


        @Override
        public int getPageCount() {
            return data1.size()-1;
        } 

        private Bitmap loadBitmap(int width, int height, final int index) throws MalformedURLException, IOException {
            Bitmap b = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
            b.eraseColor(0xFFFFFFFF);
            Canvas c = new Canvas(b);

            System.out.println("value of current page index "+mCurlView.getCurrentIndex()+" and index is "+index);

            System.out.println("url forward");
            aq.ajax(data1.get(index+1), Bitmap.class,0, new AjaxCallback<Bitmap>() {

                @Override
                public void callback(String url, Bitmap object, AjaxStatus status) {
                    if(object!=null)
                           try {
                                System.out.println("url image downloaded "+url);
                                y=object;

                                aq.ajax(data1.get(index).replace(".png", ".mp3"), File.class,0,new AjaxCallback<File>() {
                                    @Override
                                    public void callback(String url, File object, AjaxStatus status) {

                                        System.out.println("url sound downloaded "+url);
                                        try {
                                              if(object!=null)
                                               {    
                                                FileInputStream inputStream = new FileInputStream(object);

                                                if(index>0)
                                                 {  
                                                  mPlayer.stop();
                                                  mPlayer.reset();
                                                 }

                                                prepareMediaPlayer(inputStream.getFD());
                                                inputStream.close();
                                               }
                                            }
                                        catch (Exception e) {}
                                   }
                                });     
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                }
            }); 


            d = new BitmapDrawable(getResources(),y);

            if(y!=null)
            {   
            int margin = 7; 
            int border = 3;
            Rect r = new Rect(margin, margin, width - margin, height - margin);

            int imageWidth = r.width() - (border * 2);
            int imageHeight = imageWidth * d.getIntrinsicHeight()
                    / d.getIntrinsicWidth();
            if (imageHeight > r.height() - (border * 2)) {
                imageHeight = r.height() - (border * 2);
                imageWidth = imageHeight * d.getIntrinsicWidth()
                        / d.getIntrinsicHeight();
            }

            r.left += ((r.width() - imageWidth) / 2) - border;
            r.right = r.left + imageWidth + border + border;
            r.top += ((r.height() - imageHeight) / 2) - border;
            r.bottom = r.top + imageHeight + border + border;

            Paint p = new Paint();
            p.setColor(0xFFC0C0C0);
            c.drawRect(r, p);
            r.left += border;
            r.right -= border;
            r.top += border;
            r.bottom -= border;

            d.setBounds(r);
            d.draw(c);
            }
            //}
            if(y==null)
            return null;

            else
            return b;   
        }

        @Override
        public void updatePage(CurlPage page, final int width, final int height, final int index) {

                Bitmap front = null;

                System.out.println("motion / index value /countIteration / size of map "+motionDirection+"/"+index+"/"+countIteration+"/"+imageFilexxSm.size());

                try {


                     front=loadBitmap(width, height,index);

                    if(front!=null)
                    {
                    page.setTexture(front, CurlPage.SIDE_FRONT);
                    page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }}}

Также я попытался установить индекс с помощью метода getCurrentIndex, который предоставляется внутри класса CurlView, но он даже не работает. Обнаружено, что индекс передается правильно, но растровые изображения не обновляются.

Точнее проблема в следующем:

Когда я двигаюсь в прямом направлении, то есть 1-й, 2-й, 3-й, 4-й, 5-й ... изображения и звуки работают правильно, но когда я делаю обратное 5-й, 4-й, 3-й, 2-й, 1-й, тогда только 5-й и 4-й завиток правильный, но 3, 2 и 1 не работают. Почему это происходит?


person Prateek    schedule 27.05.2013    source источник


Ответы (2)


хм... curlpage от harism имеет свойство загружать изображение более одного при перелистывании страницы, например, если вы переворачиваете страницу с 0 на 1, curlpage загружает изображение для страницы 1 и страницы 2, а если вы перелистываете на страницу 5, curlpage загружает изображение для страницы 5 и 6, но если вы вернетесь на страницу 4, curlpage загрузит изображение для страницы 4, страницы 3 и страницы 2.

loadImage() срабатывает, когда onTouch ACTION.MOVE, поэтому вам нужно подготовить изображение, прежде чем перемещать/переворачивать страницу, иначе ваша страница станет нулевой, вам нужно загрузить ее вручную, вызвав метод updatePage() в классе CurlView.

для getCurrentIndex() вы можете проверить это в методах startCurl() и updatePage() в классе CurlView.

person dreamfighter    schedule 30.05.2013
comment
Спасибо за ответ. Можете ли вы сделать это более понятным, добавив пример кода или направление, что я делаю шаг за шагом, я имею в виду 1-й, 2-й, 3-й... - person Prateek; 30.05.2013
comment
Только за вашу помощь и время я хотел бы наградить вас моей наградой. Ну, я сам получил ответ. Все равно большое спасибо. - person Prateek; 05.06.2013
comment
приведенный выше ответ не подходит для вопроса. [email protected] - person Sardar Khan; 24.01.2017

Я надеюсь, что это сэкономит чье-то время при использовании библиотеки загрузки изображений с завитком страницы harism.

Итак, после долгих исследований я обнаружил, что библиотека загрузки изображений, которую я использовал (aquery), имеет методы, т.е. getCachedImage(String url) , getCachedFile(String url), которые не работают с потоками и возвращают null, если файл еще не кэширован в каком-либо хранилище (sdcard , каталог кеша).

Фрагмент кода, который был фактическим, сделал это для меня,

private class PageProvider implements CurlView.PageProvider {


    @Override
    public int getPageCount() {
        return data1.size()-1;
    } 

    private Bitmap loadBitmap(int width, int height, final int index) throws MalformedURLException, IOException {
        Bitmap b = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
        b.eraseColor(0xFFFFFFFF);
        Canvas c = new Canvas(b);

        System.out.println(" Index is : "+index+" Curl state : "+CurlActivity.motionDirection);

        if(index==data1.size())
        {
        lastPage=false; 
        }

        else
        {
        lastPage=true;  
        }   

        if(CurlActivity.motionDirection==11)
             {
                y=aq.getCachedImage(data1.get(index));
                f=aq.getCachedFile(data1.get(index+1).replace(".png", ".mp3"));

                if(f!=null)
                {
                FileInputStream inputStream = new FileInputStream(f);

                if(index>0)
                     {  
                        mPlayer.stop();
                        mPlayer.reset();
                     }

                 prepareMediaPlayer(inputStream.getFD());
                 inputStream.close();
               }
            }

            else
            {
                y=aq.getCachedImage(data1.get(index));

                if(jump==0)
                 { 
                  f=aq.getCachedFile(data1.get(index).replace(".png", ".mp3"));
                 }

                else
                 {
                  f=aq.getCachedFile(data1.get(index+1).replace(".png", ".mp3"));
                 }


                if(y!=null&&f!=null)
                {
                FileInputStream inputStream = new FileInputStream(f);

                if(index>0)
                     {  
                        mPlayer.stop();
                        mPlayer.reset();
                     }
                 prepareMediaPlayer(inputStream.getFD());
                 inputStream.close();
                }

                else if(y!=null && f == null)
                {
                    duration=1000;
                }

                else
                {   
                aq.progress(R.id.progress).ajax(data1.get(index+1), Bitmap.class,0, new AjaxCallback<Bitmap>() {
                @Override
                public void callback(final String urlimg, final Bitmap object1, AjaxStatus status) {
                    if(object1!=null)
                           try {
                                y=object1;

                                aq.ajax(data1.get(index).replace(".png", ".mp3"), File.class,0,new AjaxCallback<File>() {
                                    @Override
                                    public void callback(String url, File object, AjaxStatus status) {

                                        System.out.println("url sound downloaded "+url+status.getCode());
                                        try {
                                              if(object!=null||status.getCode()==404)
                                               {
                                                FileInputStream inputStream = new FileInputStream(object);

                                                if(index>0)
                                                 {  
                                                  mPlayer.stop();
                                                  mPlayer.reset();
                                                 }

                                                prepareMediaPlayer(inputStream.getFD());
                                                inputStream.close();
                                               }
                                            }
                                        catch (Exception e) {}
                                   }
                                });     
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                }
            });
           }    
        }

        d = new BitmapDrawable(getResources(),y);

        if(y!=null)
        {   
        int margin = 7; 
        int border = 3;
        Rect r = new Rect(margin, margin, width - margin, height - margin);

        int imageWidth = r.width() - (border * 2);
        int imageHeight = imageWidth * d.getIntrinsicHeight()
                / d.getIntrinsicWidth();
        if (imageHeight > r.height() - (border * 2)) {
            imageHeight = r.height() - (border * 2);
            imageWidth = imageHeight * d.getIntrinsicWidth()
                    / d.getIntrinsicHeight();
        }

        r.left += ((r.width() - imageWidth) / 2) - border;
        r.right = r.left + imageWidth + border + border;
        r.top += ((r.height() - imageHeight) / 2) - border;
        r.bottom = r.top + imageHeight + border + border;

        Paint p = new Paint();
        p.setColor(0xFFC0C0C0);
        c.drawRect(r, p);
        r.left += border;
        r.right -= border;
        r.top += border;
        r.bottom -= border;

        d.setBounds(r);
        d.draw(c);
        }

        return b;   
    }

    @Override
    public void updatePage(CurlPage page, final int width, final int height, final int index) {
            mPlayer.stop();
            mPlayer.reset();

            Bitmap front = null;

            try {

                front=loadBitmap(width, height,index);

                if(front!=null)
                {
                page.setTexture(front, CurlPage.SIDE_FRONT);
                page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

      } 
}
person Prateek    schedule 05.06.2013
comment
stackoverflow.com/ вопросов/16959530/ Можно проверить эту ветку! - person Chanakya Vadla; 06.06.2013