Android:启用/禁用按钮

时间:2016-02-12 17:20:16

标签: java android button

我想知道当用户符合某个标准时(例如,拼图板尺寸的高度和宽度大于1)时如何启用按钮后将其设置为假...

因为,根据我的以下代码,虚拟仿真器中的按钮仍处于禁用状态:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

// Class used to retrieve user-input values in order to create the puzzle board based on its
// dimensions as shown in the SecondActivity class.
public class FirstActivity extends AppCompatActivity {
// Initializes fields.
    private EditText etHeight, etWidth;
    private int height, width;
    private Button instructions, play;

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

        // Instantiates the following variables by reference ID.
        instructions = (Button)findViewById(R.id.instructionsButton);
        play = (Button)findViewById(R.id.playButton);
        play.setEnabled(false);

        instructions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(FirstActivity.this, PopUpActivity.class);
                startActivity(i);
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Instantiates the components of a dimension with Android's interfaces.
                etHeight = (EditText)findViewById(R.id.enterHeight);
                String ht = etHeight.getText().toString();

                // Convert to other data types accordingly.
                height = Integer.parseInt(ht);

                etWidth = (EditText)findViewById(R.id.enterWidth);
                String wh = etWidth.getText().toString();
                width = Integer.parseInt(wh);

                if (height > 1 && width > 1) {
                    play.setEnabled(true);
                }

                Intent i = new Intent(FirstActivity.this, SecondActivity.class);
                // Compile data to the Bundle interface.
                i.putExtra("height", height);
                i.putExtra("width", width);
                //v.setEnabled(true);
                startActivity(i);
            }
        });
    }

谢谢!

1 个答案:

答案 0 :(得分:1)

当文本符合特定条件时,只需在编辑文本的onTextChanged方法中将set enabled设置为true。