我有三个Fragments
。在每次单击按钮时,它将加载相应的Fragment
。如果我再次尝试单击该按钮,它将重新创建一个新的Fragment
并加载,但不是创建新的Fragment
,而是需要显示现有的后筹码Fragment
。
代码:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Frag1 frag1;
private Frag2 frag2;
private Frag3 frag3;
Button one,two,three;
FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerViewComponent();
registerClick();
}
private void registerClick() {
one.setOnClickListener(this);
two.setOnClickListener(this);
three.setOnClickListener(this);
}
private void registerViewComponent() {
one=(Button)findViewById(R.id.one);
two=(Button)findViewById(R.id.two);
three=(Button)findViewById(R.id.three);
}
@Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.one:
frag1=new Frag1();
frag3=new Frag3();
frag2=new Frag2();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
Fragment fragment2 = getSupportFragmentManager().findFragmentByTag("Frag1");
Log.v("Tag","Tagg::"+fragment2);
if (fragment2 instanceof Frag1){
Log.v("If","IF::"+fragment2);
}
else {
fragmentTransaction.add(R.id.stack_frame,frag1,"Frag1").addToBackStack("Frag1");
fragmentTransaction.commit();
}
break;
case R.id.two:
frag2=new Frag2();
Fragment fragment = getSupportFragmentManager().findFragmentByTag("Frag2");
Log.v("Tag","Tagg::"+fragment);
if (fragment instanceof Frag2){
Log.v("If","IF::"+fragment);
}
else {
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.stack_frame,frag2,"Frag2").addToBackStack("Frag2");
fragmentTransaction.commit();
}
break;
case R.id.three:
frag3=new Frag3();
Fragment fragment1 = getSupportFragmentManager().findFragmentByTag("Frag3");
Log.v("Tag","Tagg::"+fragment1);
if (fragment1 instanceof Frag3){
Log.v("If","IF::"+fragment1);
}
else {
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.stack_frame,frag3,"Frag3").addToBackStack("Frag3");
fragmentTransaction.commit();
}
break;
}
}
答案 0 :(得分:0)
Frag3 frag3;
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame_main);
if (fragment instanceof Frag3) {
frag3 = (Frag3) fragment;
} else {
frag3 = new Frag3();
}
-------------- OR ---------------------
Frag3 frag3 = new Frag3();
List<Fragment> fragments = getSupportFragmentManager().getFragments();
for(Fragment fragment : fragments){
if(fragment instanceof Frag3){
frag3 = (Frag3)fragment;
}
}
然后进行片段交易
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.stack_frame,frag3,"Frag3").addToBackStack("Frag3");
fragmentTransaction.commit();