Android - 将OnClickListener添加到对话框中的按钮时出错

时间:2012-07-05 02:52:03

标签: java android events onclicklistener

基本上我正在尝试将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>

2 个答案:

答案 0 :(得分:1)

变化:

Button ok = (Button) findViewById(R.id.okAddDialog);

Button ok = (Button) dialog.findViewById(R.id.okAddDialog);

答案 1 :(得分:1)

您似乎从主线程(来自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();
}