Search code examples
javaandroidxmllistenertoast

I'm unable to show toast message using addListenerOnButton


I am learning android. I am facing problem while displaying toast message upon button click. I am basically trying to display the password field's text upon a button click.

Java file

    public class MainActivityToast extends AppCompatActivity {
    private EditText passwd;
    private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_toast);
     }
    public void addListenerOnButton(){
    passwd = (EditText)findViewById(R.id.editTextPass);
    btn = (Button)findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {  
    Toast.makeText(MainActivityToast.this,passwd.getText(),Toast.LENGTH_SHORT).show();
        }
    });
    }
    }

This is my XML file.Do I have to add onClick method ? While running the app no toast message appears

XML file

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.acer.toastapplication.MainActivityToast"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">

    <EditText
    android:id="@+id/editTextPass"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="66dp"
    android:ems="10"
    android:inputType="textPassword" />

    <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editTextPass"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="54dp"
    android:text="Show Password"/>
    </RelativeLayout>

Solution

  • In your onCreate() call addListenerOnButton();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_toast);
        addListenerOnButton();
     }
    

    Now the toast will show up.