【问题标题】:Update A ListView In One Fragment From A Second Fragment从第二个片段更新一个片段中的 ListView
【发布时间】:2013-11-07 23:46:20
【问题描述】:

我有一个ViewPager,它向用户显示了 2 个片段。

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

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

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

我试过了:

  1. onResume 中初始化和设置列表适配器 片段 2。
  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


    【解决方案1】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多