2017-12-25 45 views
0

Hello :) 툴바의 ImageButton에 onClick 메서드를 추가하고 싶습니다.seflmade 도구 모음에있는 onClick이있는 ImageButton

onBackPressed()을 사용하면 작동하지만 ImageButton-Click을 사용할 수 없습니다. 응용 프로그램이 충돌하지만 콘솔에서 오류 메시지를 읽을 수 없으며 제대로 디버깅하는 방법을 찾지 못했습니다.

실종 될 수있는 것을 도와 줄 수 있습니까? 고마워요 :)

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(); 
} 

참고 : 내의 AndroidManifest.xml에 android:parentActivityName=".RoomActivity" 을 추가했다.

답변

0

이렇게 XML에서 onClick을 사용하려면 함수에 View 매개 변수를 전달해야합니다.

public void backToMain(View v){ 
+0

고맙습니다! 그리고 나서 v를'AlertDialog.Builder alertDlg = 새로운 AlertDialog.Builder (v);'에 제공해야합니다. –

+0

그럴 필요는 없습니다. '작성자 (this)'의 'this'는 컨텍스트를위한 것입니다. – VolkanSahin45