ViewPager - 所有页面中的事件仅发生在最后一页中

时间:2015-01-28 15:07:17

标签: android view android-viewpager android-pageradapter

我有一个说4页的viewPager。所有4个页面都使用相同的Xml。当我在第一页中以某种方式执行某个事件时,它总是在最后一页触发。

这是我的PagerAdapter

@Override
public Object instantiateItem(ViewGroup container, int pos) {
    View desktopView;

    OnTouchListener tl = null;

    desktopView = act.getLayoutInflater().inflate(
            act.getViewPagerLayout(groupName), null);

    RelativeLayout rr_appContainer, rr_dialogContainer;
    ImageView rr_home_container = (ImageView) desktopView
            .findViewById(R.id.imageView_forClick);

 Button buttonChange = (Button)desktopView.findViewById(R.id.B1);
 Button buttonDelete = (Button)desktopView.findViewById(R.id.B2);


    rr_appContainer = (RelativeLayout) desktopView
            .findViewById(R.id.rr_home_container);
    rr_dialogContainer = (RelativeLayout) desktopView
            .findViewById(R.id.rr_dialogView);
    ..........

   buttonDelete.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            deletestuff();

        }

 buttonChange.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            changeColorOfStuff();

        }

   .....
 return desktopView;

}

发生的事情是,当我点击第一页的buttonChange时,它应该改变第一页上的文字颜色,但实际上它正在改变最后一页的颜色。同样,buttonDelete正在删除最后一页的颜色。

无论我在哪个页面,它都反映了最后一页的更改。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

从这里给出的上下文中,deleteStuff()和changeColorOfStuff()只能是拥有适配器的Fragment / Activity的成员,或者是适配器本身。所以这些方法只能对这些类的成员起作用。 ViewPager向适配器询问它将要显示的片段。但是,ViewPager显示的片段中的文本属于该片段。要对该文本执行操作,您需要一个该片段成员的方法。通常的方法是使用自定义片段。例如:

自定义片段(内部类):

public static class CustomFragment extends Fragment {
    //members of the fragment
    TextView yourTextView;
    ...
    public static CustomFragment newInstance(int pos) {
        CustomFragment fragment = new CustomFragment();
        //get whatever info you need for this page
        Bundle args = getInfoSomehow(pos);
        fragment.setArguments(args)
        return fragment;
    }

    @Override
    public View onCreateView(Layout inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(....
        yourTextView = root.findViewById(...) //this is the text view you want to change things in
        //all the stuff you're currently doing in instantiateItem()
        return root;
    }

    private void deleteStuff() {
        //whatever you need to do. But notice that here it's acting on the TextView that belongs to this particular fragment
    }

    private void changeColorOfStuff() {...}
    ...
}

然后在你的instantiateItem(...)

@Override
public Object instantiateItem(ViewGroup container, int pos) {
    return CustomFragment.newInstance(pos);
}