如何按一下按钮并等到按下第二个按钮,反之亦然

时间:2018-01-28 15:48:34

标签: java android

你好,这是我在android studio中的代码。

public class GroupDesign extends AppCompatActivity {
    private static final String TAG = "Spectrum Inc";

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

        //button do suf

                Button lock = (Button) findViewById(R.id.lockit);
                //set what happens when pressed
                lock.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i(TAG, "This is a secure message!");
                        Toast.makeText(getApplicationContext(), "Door Locked!", Toast.LENGTH_SHORT)
                                .show();

                    }
                });
                  Button unlock = (Button) findViewById(R.id.unlockit);
                //set what happens when pressed
                unlock.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i(TAG, "This is a secure message!");
                        Toast.makeText(getApplicationContext(), "Door Unlocked!", Toast.LENGTH_SHORT)
                                .show();
                    }
                });


        }
    }

1 个答案:

答案 0 :(得分:0)

你可以有一个布尔标志。如果要隐藏按钮,请更新按钮的启用状态或甚至可见性。

boolean locked = false;
@Override 
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group_design);
    Button lock, unlock;
    lock = (Button) findViewById(R.id.lockit); //set what happens when pressed 
    lock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i(TAG, "This is a secure message!");
            Toast.makeText(getApplicationContext(), "Door Locked!", Toast.LENGTH_SHORT) .show();
            locked = true;
            unlock.setEnabled(true);
            lock.setEnabled(false); 
            }
    }); 
    unlock = (Button)     findViewById(R.id.unlockit); //set what happens when pressed 
    unlock.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i(TAG, "This is a secure message!"); 
            Toast.makeText(getApplicationContext(), "Door Unlocked!", Toast.LENGTH_SHORT) .show(); 
            locked = false;
            lock.setEnabled(true);
            unlock.setEnabled(false);
        }
    });
}
}

如果您想要隐藏按钮而不是停用按钮,则可以将setEnabled(false)替换为setVisibility(View.GONE)

或者如果你做得不多,你只需要一个按钮就可以改变标签文字。