首页 > 解决方案 > 如何在 PagerAdapter 中覆盖 getItemPosition

问题描述

我试图通过覆盖 getItemPosition() 来更新位置值,但它不起作用。请帮忙..

代码在这里 -

 @Override
    public int getItemPosition(Object object) {
        super.getItemPosition(object);
        SharedPreferences pos = ctx.getSharedPreferences("forposition", MODE_PRIVATE);
        int tom = pos.getInt("pos",0);
        Log.d("posTom","value : "+tom );
        return tom;
    }

这是 instantiateItem() 方法:

public Object instantiateItem(@NonNull ViewGroup container, int position) {

        inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.swipe,container,false);
        ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
        SharedPreferences sp = ctx.getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if((sp.getString("array", null)) == null) {
            String temp = Arrays.toString(count);
            editor.putString("array", temp);
            editor.commit();
        }
        String fetch = sp.getString("array", null);
        Log.d("positionlist ","value : "+fetch);
        fetch = fetch.substring(1, fetch.length()-1);
        String strarray[] =fetch.split(", ") ;


       /* SharedPreferences  spt= ctx.getSharedPreferences("your_shared_pref_name", MODE_PRIVATE);
        int post = spt.getInt("pos",1);*/
        Log.d("position","value : "+position );
        Log.d("posvalue","value : "+strarray[position] );
        Log.d("poscondition","value : "+(Integer.parseInt(strarray[position]) == 0) );

        if (Integer.parseInt(strarray[position]) == 0) {
                BackgroundTask task = new BackgroundTask(this);
                task.execute();
                imageView.setImageResource(img[position]);
                container.addView(v);
                strarray = setValue(position, strarray);
                String temp1 = Arrays.toString(strarray);
                editor.putString("array", temp1);
                editor.commit();
        } else {
                imageView.setImageResource(img[position]);
                container.addView(v);
        }
        SharedPreferences pos = ctx.getSharedPreferences("forposition", MODE_PRIVATE);
        SharedPreferences.Editor poseditor = pos.edit();
        poseditor.putInt("pos", position);
        poseditor.commit();
        return v;
    }

请给出解决方案如何从 instantiateItem() 方法更新位置。

标签: androidandroid-viewpagersharedpreferencesandroid-pageradapter

解决方案


推荐阅读