我添加了两个按钮,用以下代码添加和删除片段。
package com.example.home.appfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
公共类MainActivity扩展了FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.frame) != null){
if (savedInstanceState != null) {
return;
}
Button bf1 = (Button)findViewById(R.id.bf1);
Button bf3 = (Button)findViewById(R.id.bf3);
final Second secondobj = new Second();
bf1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.frame, secondobj,"hai").commit();
}
});
bf3.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(getSupportFragmentManager().findFragmentByTag("hai"));
transaction.addToBackStack("hai").commit();
}
});
}
}
}
答案 0 :(得分:0)
添加带标签的片段。您可以使用片段类名作为标记。
Second secondFragment = new Second();
getFragmentManager().beginTransaction()
.replace(R.id.frame, secondFragment,"UNIQUE_FRAGMENT_TAG")
.addToBackStack("UNIQUE_FRAGMENT_TAG").commit();
使用标签删除片段。
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragmentManager.findFragmentByTag("UNIQUE_FRAGMENT_TAG")).commit();