我有一个应用程序,ActionBarActivity
里面有两个片段,代表每个选项卡......问题是我在片段1上有一个列表,有两个值“teste”和“teste2”但是当我更改为片段2(tab2)并返回再次到 tab1 它会重复列表中的值,例如 "teste","teste2", "teste" , "teste2" 我怎样才能防止这种情况发生?
TabActionBarActivity:
public class TabActionBarActivity extends Activity {
String contextoId;
String BuId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_action_bar);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
String label1 = getResources().getString(R.string.label1);
Tab tab = actionBar.newTab();
tab.setText(label1);
TabListener<Tab1Fragment> tl = new TabListener<Tab1Fragment>(this, label1, Tab1Fragment.class);
tab.setTabListener(tl);
actionBar.addTab(tab);
String label2 = getResources().getString(R.string.label2);
tab = actionBar.newTab();
tab.setText(label2);
TabListener<Tab2Fragment> tl2 = new TabListener<Tab2Fragment>(this, label2, Tab2Fragment.class);
tab.setTabListener(tl2);
actionBar.addTab(tab);
BuId = getIntent().getExtras().getString("BUId");
contextoId = getIntent().getExtras().getString("CId");
Log.i("BUIdTabFrag", BuId);
}
private class TabListener<T extends Fragment> implements
ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tab_action_bar, menu);
return true;
}
希望你能帮我
“编辑”
如果我这样做:
ft.replace(android.R.id.content, mFragment, mTag).commit();
它给了我一个错误:
log: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.icenterv2/com.example.admin.TabActionBarActivity}: java.lang.IllegalStateException: commit already called
在这条线上:actionBar.addTab(tab);
和
ft.replace(android.R.id.content, mFragment, mTag);
这样它再次复制