2015-05-04 73 views
1

我曾嘗試使用下面的代碼創建一個自定義警告對話框 -訪問按鈕的警告對話框

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
LayoutInflater inflater = this.getLayoutInflater(); 

builder.setView(inflater.inflate(R.layout.dialog, null)) 
     .setTitle("test") 
     .setCancelable(true); 

AlertDialog alert11 = builder.create(); 
alert11.show(); 

這是它在警告對話框中使用的佈局dialog.xml的代碼 -

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical"> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Cancel" /> 

    <Button 
     android:id="@+id/button2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Set"/> 

</LinearLayout> 

現在,如何獲得設置點擊監聽器的按鈕的引用?

我想這一點 -

Button mButton = (Button) findViewById(R.id.button1); 

,但我得到一個異常 -

顯示java.lang.NullPointerException:試圖調用虛擬方法無效android.widget.Button.setText(java中。 lang.CharSequence)'上的空對象引用

是否有任何其他方式來訪問按鈕?

回答

1

您正在尋找放錯了地方的按鈕訪問的按鈕。

View view = inflater.inflate(R.layout.dialog, null); 
builder.setView(view) 
     .setTitle("test") 
     .setCancelable(true); 

,然後用view尋找你buotton

+0

它的工作。感謝您的回答! – Confuse

+0

不用客氣 – Blackbelt

1

你可以像這樣

Button dialogButton = (Button) alert11.findViewById(R.id.button1); 
1

一是虛增您的自定義視圖

View dialoglayout = inflater.inflate(R.layout.dialog, null); 

然後使用dialoglayout作爲

builder.setView(dialoglayout) 
    .setTitle("test") 
    .setCancelable(true); 

,現在發現按鈕

Button mButton = (Button) dialoglayout.findViewById(R.id.button1); 
1

在你的情況下使用

Button mButton = (Button)(inflater.inflate(R.layout.dialog, null)). findViewById(R.id.button1); 
1

使用此代碼,這將解決您的problem-

View view = (LinearLayout) getLayoutInflater() 
       .inflate(R.layout.dialog, null); 
AlertDialog.Builder builder = new AlertDialog.Builder(context); 
builder.setView(view); 
final AlertDialog mDialog = builder.create(); 
mDialog.setCancelable(false); 

Button mButton = (Button) view.findViewById(R.id.button1); 
mDialog.show();