我有一个视图Pager,上面有4页。所有 4 页都使用相同的 XML。当我在第一页做一个事件时,它总是在最后一页触发。
这是我的寻呼机适配器
@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;
}
正在发生的事情是,当我单击按钮从第一页更改时,它应该更改第一页上的文本颜色,但实际上它正在更改最后一页的颜色。同样,按钮删除是从最后一页删除颜色。
无论我在哪个页面,它都会在最后一页上反映这些更改。任何帮助将不胜感激。
从这里给出的上下文来看,deleteStuff() 和 changeColorOfStuff() 只能是拥有适配器或适配器本身的片段/活动的成员。因此,这些方法只能作用于这些类的成员。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() {...}
...
}
然后在您的实例化项(...)
@Override
public Object instantiateItem(ViewGroup container, int pos) {
return CustomFragment.newInstance(pos);
}