Android:如何使用onClickListener和onLongClickListener对AlertDialog进行编码

时间:2016-10-18 13:41:01

标签: java android onclicklistener alertdialog onlongclicklistener

就像标题所说的那样。我已将onClickListener编码到我的AlertDialog但我不知道如何将其放在LongLellner上。

这是我的代码:

private void addRecipeMethod() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Title");
    adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListOfRecipes"));
    builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            List<String> list = new ArrayList<>(getArrayList("ListOfRecipes"));
            getArrayListRecipes(list.get(which));
            List<String> listMain = new ArrayList<>(getArrayList("ListMain"));
            listMain.addAll(getArrayListRecipes(list.get(which)));
            saveList(listMain, "ListMain");

            adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListMain"));
            listView.setAdapter(adapter);





            //Toast.makeText(getApplicationContext(), "you have clicked " + list.get(which) , Toast.LENGTH_SHORT).show();
        }
    });
    builder.show();
}

PS。单击“菜单项”时调用void addRecipeMethod

2 个答案:

答案 0 :(得分:2)

使用自定义布局创建AlertDialog

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    // ...Irrelevant code for customizing the buttons and title
    LayoutInflater inflater = this.getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
    dialogBuilder.setView(dialogView);


    Button button = (Button)dialogBuilder.findViewById(R.id.btnName);

    button.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {

         //Commond here......

       }
   });

    button.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return false;
        }
    });

    AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

alert_label_editor xml中添加按钮,并为该按钮添加setOnLongClickListener

    Button button = (Button)dialogBuilder.findViewById(R.id.btnName);

    button.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            return false;
        }
    });

答案 1 :(得分:0)

知道为什么我不能使用findViewById方法吗?

error image

我与我的建造者有什么关系才能让它发挥作用?