2015-10-30 36 views
0

我有一個ListView它填充在我的MainActivity中,但是當我想要找到選定的項目時,所有項目顯示具有相同的位置。ListView創建一個比需要更多的項目

protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_select_teams); 

     ListView mainListView; 

     // Find the ListView in the UI. 
     mainListView = (ListView) findViewById(R.id.listView); 

     String values = "Team A vs Team B=Team C vs Team D"; 

     //Matches are send in one long string, and are separated by the = sign. 
     //This splits the string up and puts it into an array. 
     String[] array = values.split("=", -1); 

     ArrayList<String> arraylist = new ArrayList<String>(); 
     arraylist.addAll(Arrays.asList(array)); 

     ArrayAdapter listAdapter; 

     // Create ArrayAdapter using the planet list. 
     listAdapter = new ArrayAdapter<String>(this, R.layout.list_view_style, arraylist); 


     // Set the ArrayAdapter as the ListView's adapter. 
     mainListView.setAdapter(listAdapter); 

} 

這使得像這樣的列表:

Team A vs Team B [checkbox] 
Team C vs Team D [checkbox] 

我有一個按鈕,並且點擊時運行此方法:

public void matchStart(View view){ 

    String selectedMatch = String.valueOf(((ListView) findViewById(R.id.listView)).getSelectedItemPosition()); 

    Toast.makeText(SelectTeams.this, selectedMatch, Toast.LENGTH_SHORT).show(); 


} 

但是每當我點擊該按鈕,無論列表視圖中的哪個項目被選中,toast都顯示相同的值。爲什麼是這樣?

+0

你得到列表中的位置,您所需要的,請使用適配器 –

回答

0

您應該使用適配器getView方法,像這樣:

@Override 
public View getView(final int position, View convertView, ViewGroup parent) { 
    LayoutInflater inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    if (convertView == null) { 
     convertView = inflater.inflate(R.layout.some_layout, parent, 
       false); 
     convertView.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      //here get what you need by the position 

     } 
    }); 
    } 


} 
+0

的getView方法,我怎麼會相對實現這一點,林新的android。 – sam

+0

這並不複雜,只需擴展ArrayAdapter,然後按照我的回答進行操作。我會編輯我的答案,所以會更詳細。 –

+0

其實這將是好得多,然後我試圖解釋: http://www.vogella.com/tutorials/AndroidListView/article.html#arrayAdapter –

相關問題