【发布时间】:2013-11-07 23:46:20
【问题描述】:
我有一个ViewPager,它向用户显示了 2 个片段。
片段 1 包含一个带有
onClickListener的按钮,该按钮向片段 2 中的ListView内容添加一个条目。新条目是由随机数生成器生成的数字。片段 2 包含一个
ListView,其中包含一些随机数。
我找不到从片段 1 中的按钮侦听器刷新片段 2 中的列表的方法。我该怎么做?
我试过了:
- 在
onResume中初始化和设置列表适配器 片段 2。 - 从片段 1 调用
myViewPager.notifyDataSetChanged。
上述方法均未奏效。有什么想法吗?
编辑:这是我的代码:
layout_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
layout_frag_one.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/main_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Add Number" />
</RelativeLayout>
layout_frag_two
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
MainActivity
public class SlideActivity extends FragmentActivity {
private final static int FRAGMENT_NUMBER = 2;
private ViewPager pager;
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_mainpager);
pager = (ViewPager) findViewById(R.id.mainpager);
pager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
super.onCreate(savedInstanceState);
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int index) {
switch(index){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
return new Fragment1();
}
}
public int getCount() {
return FRAGMENT_NUMBER;
}
}
}
【问题讨论】:
标签: android listview android-listview android-fragments android-viewpager