单击按钮时片段会不断添加

时间:2017-11-10 04:07:36

标签: android fragment

ImageButton imageButton3 =(ImageButton)view.findViewById(R.id.item_two_timer_id);

imageButton3.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         getFragmentManager().beginTransaction()
                    .replace(R.id.container2_main , new TimerFragment2())
                              .addToBackStack(null)
                              .commit();

3 个答案:

答案 0 :(得分:1)

添加片段时添加一个标签来识别它。按标签注释片段并查看片段是否存在。如果不存在则创建一个新实例并添加它。

ImageButton imageButton3 = (ImageButton) view.findViewById(R.id.item_two_timer_id);

imageButton3.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        TimerFragment2 timerFragment2;
        timerFragment2 = (TimerFragment2) getFragmentManager().findFragmentByTag(TimerFragment2.class.getSimpleName());
        if(timerFragment2==null){
            timerFragment2=new TimerFragment2();
            getFragmentManager().beginTransaction()
                        .replace(R.id.container2_main,  timerFragment2,TimerFragment2.class.getSimpleName())
                        .addToBackStack(TimerFragment2.class.getSimpleName())
                        .commit();
        }else {
            //Dont create fragment again
        }

    }
});

答案 1 :(得分:0)

如果您要设置一个片段,请尝试使用此代码

onResume()

如果要将一个片段替换为另一个片段。

private void initFragment() {
    SelectTypeFragment fragment = new SelectTypeFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right); //if you want to set animation
    fragmentTransaction.replace(R.id.fl_addvehicle, fragment);
    fragmentTransaction.commit();
}

答案 2 :(得分:0)

您可以在片段中查看,但首先,

你需要创建一个Fragment TimerFragment2 的对象,并检查它是否可见 timerFragment.isVisible()

    ImageButton imageButton3 =(ImageButton)view.findViewById(R.id.item_two_timer_id);
TimerFragment2 timerFragment = new TimerFragment2();

imageButton3.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        if(!timerFragment.isVisible())
           getFragmentManager().beginTransaction()
                    .replace(R.id.container2_main , timerFragment)
                              .addToBackStack(null)
                              .commit();