Add onlongclick listener to an alertdialog

前端 未结 1 1814
灰色年华
灰色年华 2021-01-13 05:34

I have an AlertDialog in android that contains a list of buddies from sqlite. When I click on the buddy name in the list, that buddy is called. What I want to do is add a lo

相关标签:
1条回答
  • 2021-01-13 06:11

    one way to add an OnLongClickListener is by overriding the dialog's OnShowListener and setting an OnItemLongClickListener from within the onShow(DialogInterface dialog) method. Give this a try:

    private void displayBuddyList(String region) {
        final String region2 = region;
        Context context = getApplicationContext();
        dh = new DataBaseHelper(context);
        List<String> bnames = dh.selectBuddies(); 
        Log.d(TAG, "Buddy Names: " +bnames);
    
    final CharSequence[] buds = bnames.toArray(new CharSequence[bnames.size()]);
    //  final CharSequence[] items = {"Mark", "Vikrant", "Olle,"Jane","Dan"};
    
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select a Buddy");   
    builder.setItems(buds, new DialogInterface.OnClickListener() 
    {
        public void onClick(DialogInterface dialogInterface, int item) {
        //  showShortToast("Clicked on:"+buddy[item]);
            String ptcode =  buds[item].toString();;
        if (region2 == "A") { 
                callbuddy(ptcode,region2);
            } else if  (region2 == "E") {
                        callbuddy(ptcode,region2);
           } else if  (region2 == "P") {
                        callbuddy(ptcode,region2);
            } else {
                 showShortToast("We have a bug"); 
            }
           return;
        }
    });
    
    final AlertDialog ad = builder.create(); //don't show dialog yet
    ad.setOnShowListener(new OnShowListener() 
    {       
        @Override
    public void onShow(DialogInterface dialog) 
    {       
            ListView lv = ad.getListView(); //this is a ListView with your "buds" in it
            lv.setOnItemLongClickListener(new OnItemLongClickListener() 
        {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) 
        {
            Log.d("Long Click!","List Item #"+position+"was long clicked");
            return true;
        }           
        });     
    }
    });
    ad.show();
    

    }

    0 讨论(0)
提交回复
热议问题