我正在使用带有Pager适配器的viewpager并在适配器中传递一个arraylist。 arraylist在开始时的大小为“0”但是一旦填充,我就调用了viewpager.notifydatasetchanged()。在调用notifydatasetchanged之后,没有调用方法 CharSequence getPageTitle(int position)并且标题不是动态更新。
我的适配器代码:
public class MyViewPagerAdapter extends PagerAdapter {
private ArrayList<String> arrayList;
private Activity activity;
public ViewPagerAdapter(Activity activity, ArrayList<String> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, Object o) {
return o == view;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = activity.getLayoutInflater().inflate(R.layout.pager_item,
container, false);
// Add the newly created View to the ViewPager
container.addView(view);
// Retrieve a TextView from the inflated View, and update it's text
TextView tvWeatherDescription = view.findViewById(R.id.tv);
// Return the View
return view;
}
@Override
public CharSequence getPageTitle(int position) {
return arrayList.get(position);
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
我的活动代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> arrayList = new ArrayList<String>
ViewPager viewpager = findviewbyId(R.id.viewpager);
MyViewPagerAdapter adapter = new MyViewPagerAdapter(MainActivity.this, arraylist);
viewpager.setAdapter(adapter);
SlidingTabLayout slidingTabLayout = findViewById(R.id.sliding_tabs);
slidingTabLayout.setViewPager(viewpager);
}
一旦arraylist的大小改变了,我就这样称呼它:
arraylist.add("Item1")
adapter.notifydatasetchanged();
但标题值没有改变。有没有办法在notifydatasetchanged之后调用方法CharSequence getPageTitle(int position)?