Android ListView - 如何对项目点击做出反应?

时间:2013-05-31 12:13:51

标签: android listview

假设我有ListView个项目。我想这样做,当用户点击某个项目时,该应用会弹出一个包含该项目名称的Toast。例如,当用户点击“Apple”时,会向他们展示吐司:“你吃了Apple”。我怎么能这样做?

4 个答案:

答案 0 :(得分:1)

使用.setOnItemClickListener()的标准方式。

答案 1 :(得分:0)

像那样使用

ActivityListView .java

package com.sunil;  

    import android.app.ListActivity; 
    import android.os.Bundle; 
    import android.view.View; 
    import android.widget.ArrayAdapter; 
    import android.widget.ListView; 
    import android.widget.Toast; 

    public class ActivityListView extends ListActivity {

     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // Create an array of Strings, that will be put to our ListActivity 
     String[] namesArray = new String[] { "Linux", "Windows7", "Eclipse", 
        "Suse", "Ubuntu", "Solaris", "Android", "iPhone" }; 

     /* Create an ArrayAdapter, that will actually make the Strings above
      appear in the ListView */ 

     this.setListAdapter(new ArrayAdapter<String>(this, 
       android.R.layout.simple_list_item_1, namesArray)); 
     } 
      @Override 
      protected void onListItemClick(ListView l, View v,  
      int position, long id) { 
     super.onListItemClick(l, v, position, id); 

     // Get the item that was clicked 

     Object o = this.getListAdapter().getItem(position); 
     String keyword = o.toString(); 
     Toast.makeText(this, "You selected: " + keyword,  
       Toast.LENGTH_SHORT).show(); 
     } 
    } 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 

    <LinearLayout 

     xmlns:android="http://schemas.android.com/apk/res/android" 

     android:orientation="vertical" 

     android:layout_width="fill_parent" 

     android:layout_height="fill_parent"> 

     <TextView 

      android:layout_width="fill_parent" 

      android:layout_height="wrap_content" 

      android:text="@string/hello" /> 

    </LinearLayout> 

答案 2 :(得分:0)

你可以在列表视图上设置项目点击监听器,即

listvw=(ListView)findViewById(R.id.listviewid);

listvw.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

            Toast.makeText(ActivityName.this, "Text message", Toast.LENGTH_SHORT).show();

        }
    });

答案 3 :(得分:0)

试试这段代码          列表视图=(ListView中)findViewById(R.id.listid);

    listview.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) {

       // to set your list item or name  

        //here list is your list that you set in your adapter       
          list.get(pos);

    }
});