Thursday, November 5, 2020

How to clear EditText in Android

Tags: How to clear EditText in Android, EditText in Android, EditText in Android Example, clear EditText in Android Example, Android example, Code Android example.

How to clear EditText in Android

activity_main.xml

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/rl"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:padding="10dp"

    tools:context=".MainActivity"

    android:background="#d2d2d4"

    >

    <EditText

        android:id="@+id/et"

        android:layout_width="250dp"

        android:layout_height="wrap_content"

        android:hint="Input your country"

        android:padding="10dp"

        />

    <EditText

        android:id="@+id/et_city"

        android:layout_width="250dp"

        android:layout_height="wrap_content"

        android:hint="Input your City"

        android:padding="10dp"

        android:layout_below="@+id/et"

        />

    <Button

        android:id="@+id/btn"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Clear Text"

        android:layout_below="@id/et_city"

        />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout

        final EditText et = (EditText) findViewById(R.id.et);

        final EditText et_city = (EditText) findViewById(R.id.et_city);

        Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                // Set the first EditText empty

                et.setText("");

                // Clear the second EditText

                et_city.getText().clear();

            }

        });

 }

}

No comments:

Post a Comment