从第二个片段更新一个片段中的ListView

时间:2013-11-07 23:46:20

标签: android listview android-listview android-fragments android-viewpager

我有一个显示用户2个片段的ViewPager

  • 片段1包含一个带有onClickListener的按钮,该按钮为片段2中的ListView内容添加条目。新条目是由随机数生成器生成的数字。

  • 片段2包含ListView,其中包含一些随机数。

我找不到从片段1中的按钮侦听器刷新片段2中的列表的方法。我该怎么做?

我试过了:

  1. onResume中初始化和设置列表适配器 片段2。
  2. 从片段1中调用myViewPager.notifyDataSetChanged
  3. 上述两种方法都没有奏效。有什么想法吗?


    编辑:这是我的代码:

    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;
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

相关问题