小编典典

在主要活动中按钮不可见

java

我在主要活动中创建了三个按钮。我为按钮一使用了以下代码

`btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn.setVisibility(GONE);
btn1.setVisibility(GONE);
btn2.setVisibility(GONE);
FragmentManager fm = getSupportFragmentManager();
TestFragment fragment = new TestFragment();
fm.beginTransaction().add(R.id.fragment_container,fragment).addToBackStack(null.commit();`

问题是当我按下后退按钮而不是在主要活动中不可见的按钮时。


阅读 195

收藏
2020-11-26

共1个答案

小编典典

如果您按下返回按钮,则会返回活动状态,但是您已经将按钮的可见性设置为“消失”,这就是为什么您看不到这些按钮的原因。您必须处理后退按钮,并将按钮的可见性再次设置为“可见”。

public class MainActivity extends AppCompatActivity {

    Button btn, btn1, btn2;

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

        btn = findViewById(R.id.btn);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn.setVisibility(GONE);
                btn1.setVisibility(GONE);
                btn2.setVisibility(GONE);
                FragmentManager fm = getSupportFragmentManager();
                TestFragment fragment = new TestFragment();
                fm.beginTransaction().add(R.id.fragment_container, fragment).addToBackStack(null).commit();
            }
        });
    }
    //Handle your Back Button with onKeyDown method.
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Check for if Back Button is pressed. If pressed do below:
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed(); //Return your activity back.
            btn.setVisibility(View.VISIBLE);  //Set your btn's visibility as Visible.
            btn1.setVisibility(View.VISIBLE); //Set your btn1's visibility as Visible.
            btn2.setVisibility(View.VISIBLE); //Set your btn2's visibility as Visible.
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
2020-11-26