如何将Click Listener添加到ListView?

时间:2013-07-05 04:27:06

标签: android

我有一个列表视图,其中填充了我希望能够单击某个项目的国家/地区,并将其转到我播放音频的其他活动中。 我的清单查看:

public class MainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item,getResources()
    .getStringArray(R.array.countries)));
     }
    }

如何添加onClick就像你为按钮制作一个?

7 个答案:

答案 0 :(得分:5)

ListView listView = getListView(); // hear bind your listview

setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item,getResources().getStringArray(R.array.countries)));

 listView.setAdapter(ListAdapter);
 listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> listView, View itemView, int itemPosition, long itemId)
        {           

        }
    });

 }
}

答案 1 :(得分:3)

使用getListView()访问内置列表视图,并对其进行操作:

getListView().setOnItemClickListener();

,覆盖onListItemClicked()中的ListActivity

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    //--do stuff--
}

答案 2 :(得分:2)

覆盖onItemClick()方法

 @Override
 public void onItemClick(AdapterView<?> arg0, View view, int arg2,
              long arg3) {
     // TODO Auto-generated method stub          
     Intent intent = new Intent(getApplicationContext(), Activity2.class);
     startActivity(intent);

  }

答案 3 :(得分:2)

由于您的活动延长了ListActivity

  ListView lv = getListView();
  lv.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> listView, View itemView, int itemPosition, long itemId)
    {           
          Intent launchActivity = new Intent(FirstActivity.this, SecondActivity.class);
          startActivity(launchActivity);
    }
   });

答案 4 :(得分:2)

你可以使用context.getlistview()来获取listview。并将setOnItemClickListener添加到listview中。

context.getlistview().setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do whatever you want here

            }
        });

答案 5 :(得分:2)

implement OnItemClickListener放到班级

上方便

onCreate

中添加此内容
ListView listView = getListView();
listView.setOnItemClickListener(this);

然后像这样覆盖onItemClick

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
    // your code
}

答案 6 :(得分:1)

您必须使用setOnItemClickListener方法。 这是代码

 listview.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            // do your code here

        }
    });