[英]Android - Error when adding an OnClickListener to a button in a Dialog
基本上我正在嘗試將OnClickListener添加到對話框中的Button,但是通過簡單地添加偵聽器,應用程序變得不穩定並崩潰,當我嘗試捕獲它時,返回的消息為null。 謝謝你看看我的問題。
此外,如果有幫助,則在按下菜單按鈕時會觸發此操作。
創建對話框:
try {
final Dialog dialog = new Dialog(List.this);
dialog.setContentView(R.layout.adddialog);
dialog.setTitle("Add to the list");
dialog.setCancelable(true);
final EditText et = (EditText) findViewById(R.id.itemAddDialog);
Button ok = (Button) findViewById(R.id.okAddDialog);
Button cancel = (Button) findViewById(R.id.cancelAddDialog);
ok.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//Contents of this function don't matter, It freezes simply by being created
}
});
dialog.show();
}
catch (Exception e) {
Toast.makeText(List.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
(略微修剪)XML文件:
<LinearLayout
android:id="@+id/btnpaneAddDialog"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal" >
<Button
android:id="@+id/okAddDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add it" />
<Button
android:id="@+id/cancelAddDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" />
</LinearLayout>
更改:
Button ok = (Button) findViewById(R.id.okAddDialog);
至
Button ok = (Button) dialog.findViewById(R.id.okAddDialog);
看來你正在調用重方法net.startRunning();
從主線程(從OnClick()
方法內部)。 正確的方法是在新線程上運行該方法,例如:
@Override
public void onClick(View arg0)
{
String toSend = "";
for(String s : items)
{
if(s != null && !s.equals("")) toSend += s + ":";
}
new AsyncTask<Void, Void, Void>()
{
@Override
protected Void doInBackground(Void... params)
{
net.startRunning();
net.sendMessage("setlist|" + uname + "#" + (toSend += et.getText().toString()));
return null;
}
@Override
protected void onPostExecute(Void result)
{
dialog.dismiss();
}
}.execute();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.