2014-12-03 174 views
0

我遇到了使用listview的問題,當我點擊它時什麼都沒有發生。我想爲它點擊列表視圖項目來做一個敬酒,所以我知道它正在被點擊。我一直在努力/研究一段時間,一無所獲。有人會介意看看我是否錯過了我剛剛忽略的一些東西嗎?提前謝謝了!listView項點擊事件沒有觸發

這裏是我的類:

public class MyCar extends Activity { 

/** 
* Called when the activity is first created. 
*/ 
public ListView mylistView; 
String carInfo; 
private ArrayAdapter<String> mylistAdapter; 
ArrayList<String> arrayListCar = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_mycar); 
    mylistView = (ListView) findViewById(R.id.listView); 
    arrayListCar = new ArrayList<String>(); 
    //Just had to remove setting this adapter 2 times. Took out line below to fix. 
    mylistView.setAdapter(mylistAdapter); 

    mylistView.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, 
           long id) { 

      String item = ((TextView) view).getText().toString(); 

      Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show(); 

     } 
    }); 
} 

@Override 
protected void onStart() { 
    // TODO Auto-generated method stub 
    super.onStart(); 
    carInfo = trySomethin(); 
    fillList(); 
} 

public void fillList() { 
    String make = ""; 
    String model = ""; 

    String[] pieces = carInfo.split("\""); 
    make = pieces[3]; 
    model = pieces[7]; 

    ArrayList<String> carList = new ArrayList<String>(); 
    carList.add(make + " " + model); 
    // Create ArrayAdapter using the car list. 
    mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList); 

    mylistView.setAdapter(mylistAdapter); 
    mylistAdapter.notifyDataSetChanged(); 
} 

}

+1

你沒有看到「吐司」? – Raghunandan 2014-12-03 05:36:00

+0

是的,我沒有看到烤麪包。當我點擊它時,列表視圖保持在那裏,我可以點擊它10次,什麼也沒有發生。 – Shawn 2014-12-03 05:36:16

+0

哇,我很抱歉浪費時間,我沒有看到我將適配器設置爲mylistView 2次。刪除了onCreate中的一個,現在可以使用。感謝您的時間! – Shawn 2014-12-03 05:42:34

回答

1
Try this 


     listView.setOnItemClickListener(new OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
      int position, long id) { 

      // ListView Clicked item index 
      int itemPosition  = position; 

      // ListView Clicked item value 
      String itemValue = (String) listView.getItemAtPosition(position);    
      // Show Alert 
      Toast.makeText(getApplicationContext(), 
       "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG) 
      .show(); 

      } 
     }); 
2

,如果你有ListView項的任何元素改變這個爲他們

android:focusable="false"      

,如果你正在改變任何元素運行時可見性,每次更改其可見性時,都必須以編程方式處理焦點。