找到一个片段里面一个ListView? [英] Finding a ListView inside a Fragment?
问题描述
好吧,我试图找到一个片段里面一个ListView,能够通过创建它的主要活动添加和删除项目。这里是我的尝试(我根据它com.viewpagerindicator.sample),但是当我尝试访问mainListView到底,它崩溃。
Well, i'm trying to find a ListView inside a fragment, to be Able to add and remove items through the Main Activity that created it. here is my attempt (i based it on com.viewpagerindicator.sample), but when i try to access the mainListView in the end, it crashes.
public final class ContactListFragment extends Fragment {
private ListView MyListView;
public ListView GetListView()
{
return MyListView;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
LinearLayout theLayout = (LinearLayout) inflater.inflate(R.layout.tab_frag, container, false);
MyListView = (ListView)theLayout.findViewById(R.id.listViewx);
MyListView.setAdapter(adapter);
return theLayout;
}
}
和这里它的布局
and here it it's layout
<ListView
android:id="@+id/listViewx"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
</LinearLayout>
而这主要活动的code,我想从列表视图访问到能够修改
公共类ContactListActivity扩展BaseSampleActivity
{
and that's the code of Main Activity that i want to access listview from to be able to modify public class ContactListActivity extends BaseSampleActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, ContactListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ContactListFragment.class.getName()));
fragments.add(Fragment.instantiate(this, ContactListFragment.class.getName()));
PagerAdapter mAdapter = new PagerAdapter(getSupportFragmentManager(), fragments);
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
TabPageIndicator mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
ContactListFragment XCLF = (ContactListFragment) fragments.get(1);
ListView mainListView = (ListView) XCLF.GetListView();
}
任何帮助将是AP preciated,谢谢
any help would be appreciated, thanks
推荐答案
您将无法在活动的
片段
的意见code>的的onCreate()
为片段
的布局是不是在这个阶段充气。使用片段
的 onActivityCreated()
来更新它的的ListView
You can't get the Fragment
's views in Activity
's onCreate()
as the Fragment
's layout is not inflated in this stage. Use Fragment
's onActivityCreated()
to update it's ListView
.
从活动的onCreate
See Access Fragment View from Activity's onCreate
这篇关于找到一个片段里面一个ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!