TheD3luxed TheD3luxed - 1 month ago 8
Java Question

Android: How to code an AlertDialog with onClickListener and onLongClickListener

Like the title says. I have coded onClickListener to my AlertDialog but i don't know how to put there onLongClickListener.

This is my code:

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 is called when Menu Item is clicked

Answer

Create AlertDialog with custom layout like this

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

Add Button in alert_label_editor xml and add setOnLongClickListener for that Button

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