将按钮可单击属性设置为false

时间:2012-07-21 12:04:43

标签: android onclicklistener

我需要为Android中的按钮停用click-event。就像样本一样,我尝试过以下操作。我已将TextView命名为(输入文本)为名称。条件检查TextView是否为空按钮且可点击是否应设置为false。但是,打印Toast时不会发生这种情况。有人可以告诉我原因。此外,如果文本字段不为空,我想将clickable event按钮重置为true。

Java文件:

public class ButtonclickabkeActivity extends Activity {
    TextView tv;
    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.textView1);
        tv.setText("Name");
        btn = (Button) findViewById(R.id.button1);

        if (tv.getText().toString().length() != 0) {
            btn.setClickable(false);
            Toast.makeText(getApplicationContext(), "" + tv.getText().toString().length(), Toast.LENGTH_LONG).show();
        } else {
            btn.setClickable(true);
        }
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(getApplicationContext(), "Button clicked", Toast.LENGTH_LONG).show();
            }
        });
    }
}

XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"/>
    <TextView 
        android:text="TextView" 
        android:id="@+id/textView1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/>
    <Button 
        android:text="Button" 
        android:id="@+id/button1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/>
</LinearLayout>

3 个答案:

答案 0 :(得分:12)

使用

btn.setEnable(false);

而不是

btn.setClickable(false);

答案 1 :(得分:1)

用户370305是正确的。 .setEnable就是你要找的。或者您可以在布局XML文件中使用android:clickable

答案 2 :(得分:0)

就我而言

{{1}}