我的Android应用程序遇到了问题。当我添加两个标签时,我也有两个片段。但问题是两个标签上都出现了相同的片段。另一个片段没有显示出来。这是它的样子。
以下是我的活动代码:
public class DatabaseFiller extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.rmactivity);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setSubtitle("Created by Rohit Nandakumar");
/*ActionBar.Tab searchdb = actionBar.newTab().setText("Search Database");
ActionBar.Tab searchlist = actionBar.newTab().setText("Show List"); */
ActionBar.Tab Frag1 = actionBar.newTab().setText("Search Database");
ActionBar.Tab Frag2 = actionBar.newTab().setText("Show List");
Fragment fragment1 = new DatabaseFillerFragment();
Fragment fragment2 = new DeleteDBItems();
Frag1.setTabListener(new MyTabListener(fragment1));
Frag2.setTabListener(new MyTabListener(fragment2));
actionBar.addTab(Frag1);
actionBar.addTab(Frag2);
}
}
这是我的整个MyTabListener类:
package com.example.foodsaver2;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
public class MyTabListener implements TabListener {
public Fragment fragment;
public MyTabListener(Fragment fragment) {
this.fragment = fragment;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if (fragment == null) {
// If not, instantiate and add it to the activity
ft.add(android.R.id.content, fragment);
} else {
// If it exists, simply attach it in order to show it
ft.attach(fragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if (fragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(fragment);
}
}
}
我在这里做错了什么?关于这个问题的任何帮助将不胜感激。
答案 0 :(得分:1)
初始化侦听器,分离片段并提交它。
选中选项卡只需添加其他分段。
请参阅以下修订代码以获取帮助 -
public MyTabListener(Activity activity, String tag, Class<T> cls, Bundle args) {
mActivity = activity;
mTag = tag;
mClass = cls;
mArgs = args;
fragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
if (fragment != null) {
FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
ft.detach(fragment);
ft.commit();
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
fragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
ft.add(android.R.id.content, fragment , mTag);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
ft.detach(fragment);
}
}
答案 1 :(得分:0)
您需要在FragmentTransaction上调用commit方法来触发事务发生。