如何在Android中为ListView编写onclick事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2944120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:00:01  来源:igfitidea点击:

How to write onclick event for ListView in Android?

androidlistview

提问by Srikanth Naidu

Hi i have the listview the sixitems in it, but when i call alet function on event it doesnt work ? let me know how to write a function on item event on click?

嗨,我有六个项目的列表视图,但是当我在事件上调用 alet 函数时它不起作用?让我知道如何在单击时在项目事件上编写函数?

     public class PhotoListView extends ListActivity {
     String[] listItems = {"HeadShot", "BodyShot ", "ExtraShot", "Video Take1", "Video Take2", "Video Take3", }; 
    @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         setListAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1, listItems));
     }

OnListclick

列表点击

  ListView Shot = getListView();
  protected void onListItemClick(View view) {

    if(view == Shot){

        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

        // set the message to display
          alertbox.setMessage("Please Get Ready");

    }    

回答by Primal Pappachan

ListView Shot = getListView();

In Shot you have the id for the listview and not for each item in the list.

在 Shot 中,您拥有列表视图的 id,而不是列表中的每个项目的 id。

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);

 AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

        // set the message to display
          alertbox.setMessage("Please Get Ready").show();

    }

Or you could use ListView::setOnItemClickListener

或者你可以使用 ListView::setOnItemClickListener

public class PhotoListView extends ListActivity implements OnItemClickListener


ListView shot = getListView();
        shot.setOnItemClickListener(this);


@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

    // set the message to display
      alertbox.setMessage("Please Get Ready").show();


    }