由两个 Button 触发的两个 ListFragment

Two ListFragment triggered by two Button

这批代码只对第一次按下Button有效,无论我点击哪个Button,指定区域都会显示一个填充了正确值的ListFragment,正如所愿。但是,当我单击备用按钮时,它不会替换 fragment_container,它只会崩溃。

public void selectTamFragment(View view){
    TamInputListFragment lstfragment=(TamInputListFragment)getSupportFragmentManager().findFragmentByTag("lstfragment");

    Toast.makeText(getApplicationContext(), "You pressed tamButton", Toast.LENGTH_LONG).show();

        if(lstfragment==null){
            lstfragment=new TamInputListFragment();
            FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
            transact.add(R.id.fragment_container, lstfragment, "lstfragment");
            transact.commit();
    }

}
public void selectVerbFragment(View view){
    VerbInputListFragment lstfragment=(VerbInputListFragment)getSupportFragmentManager().findFragmentByTag("lstfragment");

    Toast.makeText(getApplicationContext(), "You pressed verbButton", Toast.LENGTH_LONG).show();

    if(lstfragment==null){
        lstfragment=new VerbInputListFragment();
        FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
        transact.add(R.id.fragment_container, lstfragment, "lstfragment");
        transact.commit();
    }

}

分享崩溃日志,不知道太多信息我猜你对两个片段使用相同的标签名称,所以尝试为每个片段使用不同的标签名称(lstfragment_1 & lstfragment_2)

public void selectTamFragment(View view){
TamInputListFragment lstfragment=(TamInputListFragment)getSupportFragmentManager().findFragmentByTag("lstfragment_1");

Toast.makeText(getApplicationContext(), "You pressed tamButton", Toast.LENGTH_LONG).show();

    if(lstfragment==null){
        lstfragment=new TamInputListFragment();
        FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
        transact.add(R.id.fragment_container, lstfragment, "lstfragment_1");
        transact.commit();
}
  }

public void selectVerbFragment(View view){
VerbInputListFragment lstfragment=(VerbInputListFragment)getSupportFragmentManager().findFragmentByTag("lstfragment_2");

Toast.makeText(getApplicationContext(), "You pressed verbButton", Toast.LENGTH_LONG).show();

if(lstfragment==null){
    lstfragment=new VerbInputListFragment();
    FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
    transact.add(R.id.fragment_container, lstfragment, "lstfragment_2");
    transact.commit();
}
}