Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set button clickable property to false

I need to disable the click-event for a button in Android. Just as a sample, I have tried doing the following. I have taken a TextView named it (entered a text) as Name. The condition checks if, TextView is empty button and clickable should be set to false. However this does not happen when the Toast is printed. Can somemone tell me the reason. Also if the text field is not empty I want to reset the clickable event for button as true.

Java File:

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 file:

<?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>
like image 852
Joyson Avatar asked Dec 03 '22 02:12

Joyson


2 Answers

Use

btn.setEnable(false);

instead of

btn.setClickable(false);
like image 146
user370305 Avatar answered Dec 29 '22 15:12

user370305


User 370305 is correct. .setEnable is what your looking for. Or you could use android:clickable in the layout XML file.

like image 23
Steven Avatar answered Dec 29 '22 14:12

Steven