如何在ViewPager页面中更改视图

时间:2013-04-08 10:44:48

标签: android layout android-viewpager

这来自我的自定义PageAdapter:

public Object instantiateItem(View collection, int position) {
    LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View view = null;
    switch (position) {
    case 0: view = dMngr.GetView(inflater); 
        break;
    case 1: view = mMngr.GetView(inflater); 
        break;
    case 2: view = cMngr.GetView(inflater); 
        break;
    }   
    ((ViewPager) collection).addView(view, 0);
    return view;
}

这是 cMngr.GetView 代码:

public View GetView(LayoutInflater inflater){
    View view = null;
    if (showCamDetail){
        view = inflater.inflate(R.layout.cam_view, null);
        ((Button)view.findViewById(R.id.button1)).setOnClickListener(myhandler2);
    } else {
        view = inflater.inflate(R.layout.cams_view, null);  
        ((ImageView)view.findViewById(R.id.imageView1)).setOnClickListener(myhandler);
    }
    return view;
}

View.OnClickListener myhandler = new View.OnClickListener() {
    public void onClick(View v) {
        showCamDetail = true;
        hPageAdapter.notifyDataSetChanged();
    }
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
        showCamDetail = false;
        hPageAdapter.notifyDataSetChanged();
    }
};

只有当我滑到第一页然后再回到第三页时,此代码才会在第三页上更改layout。 我点击layoutImageView后,我需要立即更改Button

1 个答案:

答案 0 :(得分:0)

如果两个视图状态之间的差异不是太复杂,请将它们包含在相同的布局中,并根据需要使用View.setVisibility(View.GONE)View.setVisibility(View.VISIBLE)选择性地隐藏/显示部分视图。通胀后您可以setTag()布局,以便以后findViewByTag()更容易找到它,并且您可以应用您的可见性更改。