2015-02-09 164 views
0

我花了幾個小時研究它,嘗試了不同的方法,但最接近的是獲取列表中第一項的文本 - 而不是選定的項目。Android - 從列表視圖中獲取所選項目的文本

這是我的getView方法:

public View getView(int position, View convertView, ViewGroup parent) { 
    ViewHolder holder; 
    if (convertView == null) { 
     convertView = mInflater.inflate(R.layout.row, null); 
     holder = new ViewHolder(); 
     holder.sweetName = (TextView) convertView 
       .findViewById(R.id.sweetName); 
     holder.sweetPic = (ImageView) convertView 
       .findViewById(R.id.sweetPic); 

     convertView.setTag(holder); 
    } else { 
     holder = (ViewHolder) convertView.getTag(); 
    } 


    holder.sweetPic.setImageResource(sweetPicResource[position]); 
    holder.sweetName.setText(sweetsNames[position]); 


    return convertView; 
} 

這裏是我的onClickListener從活動:

listView.setOnItemClickListener(
      new AdapterView.OnItemClickListener() 
      { 
       @Override 
       public void onItemClick(AdapterView<?> arg0, View view,int position, long arg3) { 
        String selectedSweet = listView.getItemAtPosition(position).toString(); 


        TextView textView = (TextView) listView.findViewById(R.id.sweetName); 
        String text = textView.getText().toString(); 
        Toast.makeText(getApplicationContext(), "Selected item: " + text + " - " + position, Toast.LENGTH_SHORT).show(); 

       } 
      } 
    ); 

任何想法,請?

+1

在發表問題之前,有成千上萬的問題像這樣。 – 2015-02-09 11:59:31

+0

是的,正如我上面提到的,我一直在研究它,看了很多類似的問題和答案,但沒有一個適合我。 – Alex 2015-02-09 12:01:24

+0

TextView textView =(TextView)listView.findViewById(R.id.sweetName); - > TextView textView =(TextView)view.findViewById(R.id.sweetName); – nbaroz 2015-02-09 12:01:34

回答

2
listView.setOnItemClickListener(
      new AdapterView.OnItemClickListener() 
      { 
       @Override 
       public void onItemClick(AdapterView<?> arg0, View view,int position, long arg3) { 
        String selectedSweet = listView.getItemAtPosition(position).toString(); 


        TextView textView = (TextView) view.findViewById(R.id.sweetName); 
        String text = textView.getText().toString(); 
        Toast.makeText(getApplicationContext(), "Selected item: " + text + " - " + position, Toast.LENGTH_SHORT).show(); 

       } 
      } 
    ); 
相關問題