如何动态刷新viewpager中的片段?

时间:2016-01-27 11:07:29

标签: java android android-fragments android-viewpager

我的MainActivity中有一个ViewPager(mainViewPager),它从包含另一个ViewPager(imageViewPager)和TextView的片段呈现。现在,imageViewPager从包含ImageView和按钮的另一个片段呈现。我在这个ImageView上设置了onClick监听器,它通过下方的按钮转换图像的全屏视图。现在点击这个按钮我想要返回到我的MainActivity,条件是在我输入的同一页面上与我在全屏中看到的相同图像。我能够获得相同的页面,但图像始终从0开始。

基本上我的层次结构如下:

MainActivity
   --mainViewPager-->TaskFragment
                        --imageViewPager-->ImageFragment(contains only ImageView
                        --TextView(set text returned from MainActivity)

我的代码: 的 MainActivity.java

    public class MainActivity extends FragmentActivity {

        private ViewPager mViewPager;
        private CustomPagerAdapter mPagerAdapter;
        private int changedPosition;

        private String[] vehicles = new String[]{"Audi Q7", "Honda Accord", "Hyundai i20", "Maruti Suzuki Swift", "Mahindra XUV 500",
                "Swift Dzire", "Honda City", "Honda Civic", "Mercedez Benz", "Rolls Royce", "Ferrari"};

        private String[][] vehicle_info = new String[][]{
                {"http://www.hdwallpapers.in/walls/2010_abt_audi_q7_3_tdi_3-wide.jpg",
                        "http://www.hdwallpapers.in/walls/2010_mtm_audi_s5_cabrio_michelle_edition-wide.jpg",
                        "http://www.hdwallpapers.in/walls/2009_audi_tts_coupe_car-wide.jpg"},
                {"http://automobiles.honda.com/images/2015/accord-sedan/exterior-gallery/2015-honda-accord-sedan-sport-exterior-side1.jpg",
                        "http://www.carprousa.com/wp-content/uploads/2015/01/HondaInterior-e1421978263126.jpg",
                        "http://www.carprousa.com/wp-content/uploads/2015/01/HondaInterior2-e1421978365916.jpg"},
                ...........
};


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            mViewPager = (ViewPager)findViewById(R.id.mainViewPager);
            mPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), vehicles, vehicle_info);
            mViewPager.setAdapter(mPagerAdapter);

        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 0) {

                changedPosition = data.getIntExtra("CHANGED_POSITION", 0);
                Log.i("POSITION 3:"," "+changedPosition);

                TaskFragment fragment = new TaskFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("IMAGE_POSITION", changedPosition);
                fragment.setArguments(bundle);
            }
        }

    }

activity_main.xml中

 <android.support.v4.view.ViewPager
        android:id="@+id/mainViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    </android.support.v4.view.ViewPager>

CustomPagerAdapter.java

public class CustomPagerAdapter extends FragmentStatePagerAdapter{

    private String[] vehicles,selected_vehicle_info;
    private String[][] vehicle_info;

    public CustomPagerAdapter(FragmentManager fragmentManager,String[] vehicles,String[][] vehicle_info){
        super(fragmentManager);
        this.vehicles = vehicles;
        this.vehicle_info = vehicle_info;
    }

    @Override
    public Fragment getItem(int position) {

        selected_vehicle_info = vehicle_info[position];

        TaskFragment taskFragment = new TaskFragment();

        Bundle bundle = new Bundle();
        bundle.putString("ITEM",vehicles[position]);
        bundle.putStringArray("ITEM_INFO",selected_vehicle_info);
        taskFragment.setArguments(bundle);

        return taskFragment;
    }

    @Override
    public int getCount() {
        return vehicles.length;
    }
}

TaskFragment.java

public class TaskFragment extends Fragment {

    private String vehicle;
    private String[] vehicle_info;
    private ViewPager imageViewPager;
    private ImagePagerAdapter imagePagerAdapter;
    private int changedImagePosition;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        vehicle = getArguments().getString("ITEM");
        vehicle_info = getArguments().getStringArray("ITEM_INFO");

        View view = inflater.inflate(R.layout.activity_task_fragment,container,false);
        TextView messageTextView = (TextView) view.findViewById(R.id.textView);
        messageTextView.setText(vehicle);

        imageViewPager = (ViewPager)view.findViewById(R.id.imageViewPager);

        imagePagerAdapter = new ImagePagerAdapter(getActivity(), vehicle_info);
        imagePagerAdapter.notifyDataSetChanged();
        imageViewPager.setAdapter(imagePagerAdapter);
        imageViewPager.setCurrentItem(changedImagePosition);

        return view;
    }

    private class ImagePagerAdapter extends PagerAdapter {

        private Activity activity;
        private String[] vehicle_info;

        public ImagePagerAdapter(Activity activity,String[] vehicle_info){
            this.activity = activity;
            this.vehicle_info = vehicle_info;
        }

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

            LayoutInflater inflater = LayoutInflater.from(activity);
            View view = inflater.inflate(R.layout.activity_image_fragment,container,false);
            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);

            Picasso.with(getContext()).load(vehicle_info[position]).into(imageView);

            if(imageView.getParent()!=null)
                ((ViewGroup)imageView.getParent()).removeView(imageView);

            ((ViewPager) container).addView(imageView, 0);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, ImageInFullScreen.class);
                    intent.putExtra("IMAGES_URL", vehicle_info);
                    intent.putExtra("IMAGE_POSITION", position);
                    activity.startActivityForResult(intent, 0);
                }
            });
            return imageView;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
            return vehicle_info.length;
        }

        @Override
        public void destroyItem(ViewGroup collection, int position, Object view) {
            collection.removeView((View) view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

}

ImageInFullScreen.java

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("CHANGED_POSITION",changedImgPosition);
                setResult(0,intent);}});

//和相同的适配器n。

2 个答案:

答案 0 :(得分:0)

在哪里想要刷新视图,请输入以下代码

this.page_position = 0;
imagePagerAdapter.notifyDataSetChanged();

并在您的ImagePagerAdapter中覆盖以下函数 -

@Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

POSITION_NONE表示无论何时调用notifyDataSetChanged,适配器都会创建新视图而不是使用相同的视图。

这应该适用于我们的情况。

答案 1 :(得分:0)

我找到了一个问题的答案,问题是我的setCurrentItem()不知道在TaskFragment的onCreateView()中工作,所以我把它移到了Run方法Runnable接口的postAtTime()nd然后它工作得很好。

这是我编辑过的代码。

<强> MainActivity.java `

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0) {

            claim_id = vehicleDetailsArrayList.get(changedPage).getClaimId();

            //Retrieve value of position of last viewed image, before clicking the button
            changedPosition = data.getIntExtra("CHANGED_POSITION", 0);
            Log.i("POSITION 3:"," "+changedPosition);

            if(changedPage > -1 && changedPage < vehicleDetailsArrayList.size()) {
                addUpdateImagePositionInList(claim_id, changedPosition);
            }

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mViewPager.getAdapter() != null) {
                        mViewPager.getAdapter().notifyDataSetChanged();
                    }
                }
            }, 0);
        }
    }

    public void addUpdateImagePositionInList(int claimId, int position){
        for (int imageLength = 0; imageLength < imagePositionArrayList.size(); imageLength++)
        {
            if (claimId == (imagePositionArrayList.get(imageLength).getClaim_id()))
            {
                imagePositionArrayList.get(imageLength).setImagePosition(position);
                return;
            }
        }
        imagePositionArrayList.add(new ImagePosition(claimId, position));
    }

    public int getChangedImagePosition(int claimId){
        for (int imageLength = 0; imageLength < imagePositionArrayList.size(); imageLength++)
        {
            if (claimId == (imagePositionArrayList.get(imageLength).getClaim_id()))
            {
                Log.i("POSITION123 ","  ::"+ imagePositionArrayList.get(imageLength).getImagePosition() );
                return imagePositionArrayList.get(imageLength).getImagePosition();
            }
        }
        return 0;
    }
`

<强> TaskFragment.java `

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        id = getArguments().getInt("ID");
        vehicle = getArguments().getString("ITEM");
        vehicle_info = getArguments().getStringArray("ITEM_INFO");

        changedImagePosition = ((MainActivity)getActivity()).getChangedImagePosition(id);
        View view = inflater.inflate(R.layout.task_fragment,container,false);
        TextView messageTextView = (TextView) view.findViewById(R.id.textView);
        messageTextView.setText(vehicle);

        imageViewPager = (ViewPager)view.findViewById(R.id.imageViewPager);
        imagePagerAdapter = new ImagePagerAdapter(getActivity(), vehicle_info);
        imageViewPager.setAdapter(imagePagerAdapter);

        /*The below code doesn't work
        if (imageViewPager.getCurrentItem() != changedImagePosition) {

            Log.i("POSITION current", ":" + imageViewPager.getCurrentItem());
            Log.i("POSITION changed", " :"+ changedImagePosition);

            setCurrentItem = true;
            imageViewPager.setCurrentItem(changedImagePosition, false);
            Log.i("POSITION getCurrent", " :" + imageViewPager.getCurrentItem());
        }
        */


        new Handler().postAtTime(new Runnable() {
            @Override
            public void run() {
                if (imageViewPager.getAdapter() != null) {
                    imageViewPager.getAdapter().notifyDataSetChanged();
                    imageViewPager.setCurrentItem(changedImagePosition);
                }
            }
        },0);

        return view;
    }
`