Android Studio显示和隐藏片段

时间:2017-01-06 01:39:24

标签: android android-fragments

我正在制作一个测验应用程序,其中标记显示在屏幕的左侧,按下它们时,您必须猜测它所属的国家/地区右侧的Fragment。屏幕。因此,当按下标记时,您应该被带到Fragment,您可以输入答案。 Aka每个标志都有自己的Fragment。但是,我在使用代码时遇到了一些问题。

无论我点击哪一个按钮(/标志),所有片段都会立即出现。但是,我只想让它们一次出现一个。我试过在我的代码中插入一个if语句,但我觉得我错过了一些东西。 非常感谢所有的帮助!

解决方案是在if语句中添加.show().hide()吗?

Play.java

import android.graphics.Color;
import android.os.Bundle;
import android.app.FragmentManager;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.widget.ImageButton;

import layout.FragmentOne;
import layout.FragmentTwo;

public class Play extends MainActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);

    final ImageButton imageBtn10 = (ImageButton)findViewById(R.id.imageButton10);
    imageBtn10.setOnClickListener(new View.OnClickListener()      {
           @Override
            public void onClick(View v) {
                 FragmentManager fragMan = getFragmentManager();
                 FragmentTransaction fragTrans = fragMan.beginTransaction();
                 FragmentOne f1 = new FragmentOne();
                 fragTrans.replace(R.id.fragment_place, new FragmentOne());
                 fragTrans.addToBackStack(null);
                 fragTrans.commit();
           }
    });

    final ImageButton imageBtn9 = (ImageButton)findViewById(R.id.imageButton9);
    imageBtn9.setOnClickListener(new View.OnClickListener()      {

           @Override
            public void onClick(View v) {
               if(v.equals(imageBtn9)) {               
                 FragmentManager fragMan = getFragmentManager();
                 FragmentTransaction fragTrans = fragMan.beginTransaction();
                 FragmentTwo f2 = new FragmentTwo();
                 fragTrans.replace(R.id.fragment_place2, new FragmentTwo());
                 fragTrans.addToBackStack(null);
                 fragTrans.commit();
                                      }
           }
    });
  }
}

0 个答案:

没有答案
相关问题