如何在listdialog的点击事件中获取所选项目?

时间:2016-04-14 19:30:15

标签: java android dialog

我正在实施listdialog。我想点击特定的listitem时打印一个Toast消息。我想在吐司上打印消息,否则我想要执行一些操作。我的代码是这样的:

ListView lv;
DbHelper dbh;
final String ar[]={"Delete","Update"};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_all);
    lv = (ListView) findViewById(R.id.listView);
    dbh = new DbHelper(ViewAllActivity.this);

    ArrayList<DoctorPojo> arraylist = dbh.getData();
    ArrayAdapter<DoctorPojo> adapter=new ArrayAdapter<DoctorPojo>(ViewAllActivity.this,android.R.layout.simple_list_item_1,arraylist);
    lv.setAdapter(adapter);

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
    {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
        {

            final AlertDialog.Builder alert=new AlertDialog.Builder(ViewAllActivity.this);
            alert.setTitle("Which Action You Want to Perform...!!!");
            alert.setItems(ar, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if(ar[0] == alert.) {
                        Toast.makeText(ViewAllActivity.this, " Delete is pressed", Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(ViewAllActivity.this, " Update is pressed", Toast.LENGTH_LONG).show();
                    }
                }
            });
            alert.create().show();
            return false;
        }
    });
    }

}

请帮忙;我对if条件感到困惑。

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,则需要实施ListView's setOnItemClickListener(AdapterView.OnItemClickListener listener)。 setOnItemLongClickListener用于按下并按住列表项。

对于ListView的setOnItemClickListener()实现,您可以执行以下操作:

lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
             //YOUR ACTION HERE
             //or show a toast instead:
             Toast.makeText(ViewAllActivity.this, "Your message here", Toast.LENGTH_LONG).show();
        }
    });