[英]How can I refresh a ListView in a Fragment from the main Activity?
我有一個MainActivity
,它包含一個帶有兩個片段的標簽欄: MainFragment
和WishlistFragment
。 它們都擴展為ListFragment
。
當有人觸摸選項菜單中的菜單項時,我希望顯示的片段中的ListView使用名為LazyAdapter adapter
自定義適配器刷新其列表。
所以在這里我希望刷新進入我的MainActivity
代碼:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit:
// find out which fragment is showing here
// refresh the fragment's listview here
// adapter.notifyDataSetChanged();
return true;
}
}
我怎樣才能做到這一點? 我不知道如何調用片段以及如何確定顯示哪個片段。
以下是我在MainActivity
設置標簽的方法:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar.addTab(actionBar.newTab().setText("Main").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Wishlist").setTabListener(this));
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the container
ListFragment newfragment = null;
switch (tab.getPosition() + 1)
{
case 1:
newfragment = new MainFragment();
break;
case 2:
newfragment = new WishlistFragment();
break;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, newfragment)
.commit();
}
我怎樣才能做到這一點?
步驟1:修復onTabSelected()
。 每次用戶選擇選項卡時,您都不希望創建新片段。 相反,您希望有兩個片段,由數據成員中的活動保留,並在replace()
事務中使用它們。
步驟#2:需要時,在ActionBar
上調用getSelectedNavigationIndex()
,用它來選擇你需要的兩個片段中的哪一個(從上面步驟1中提到的數據成員中獲得),並調用片段上的一些方法來做什么你要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.