Search code examples
androidonclickcrashandroid-toolbarandroid-imagebutton

ImageButton with onClick in a seflmade Toolbar


Hello :) I would like to add an onClick method to an ImageButton in a Toolbar.

It works using onBackPressed() but not by ImageButton-Click. The App is crashing but I am not able to read the error-message from the console and I didn't figure out how to debug it properly yet.

Can you help me out what could be missing? Thanks a lot :)

toolbar_room.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar_room"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton
        android:layout_width="?attr/actionBarSize"
        android:layout_height="match_parent"
        android:background="@drawable/ic_back"
        android:id="@+id/btn_roomBack"
        android:onClick="backToMain"/>
</LinearLayout>

activity_room.xml

<android.support.v7.widget.LinearLayoutCompat 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="de.hftl.smartcast.RoomActivity"
android:orientation="vertical">

<include layout="@layout/toolbar_room"></include>
//Code

RoomActivity.java

public class RoomActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_room);
}
public void backToMain(){
    AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
    alertDlg.setMessage("Text");
    alertDlg.setCancelable(false);

    alertDlg.setPositiveButton("yeah", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            RoomActivity.super.onBackPressed();
        }
    });
    alertDlg.setNegativeButton("nope", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
        }
    });
    alertDlg.create().show();
}

Note: I added android:parentActivityName=".RoomActivity" to my AndroidManifest.xml.


Solution

  • You should pass View parameter to function for use onClick from XML like this.

    public void backToMain(View v){