1

我有自定義適配器的列表視圖,我有按鈕。如何更改自定義適配器上的按鈕點擊按鈕文本

所以我想改變按鈕上的按鈕文本點擊位置上的特定項目。

<LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 

     > 

     <TextView 
      android:id="@+id/name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      /> 

    </LinearLayout> 

    <Button 
     android:id="@+id/btnadd" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="ADD"/> 

我的自定義適配器:

static class ViewHolder { 
    public TextView name; 
    public Button btnadd; 
} 

@Override 
public View getView(final int position, final View convertView, 
        ViewGroup parent) { 
    final ViewHolder holder; 
    View v = convertView; 

    if (v == null) { 
     final LayoutInflater vi = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = vi.inflate(R.layout.row_brandselected, null); 
     holder = new ViewHolder(); 

     holder.name = (TextView) v.findViewById(R.id.name); 


     holder.btnadd = (Button) v.findViewById(R.id.btnadd); 

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

    UserName mUserNrand = values.get(position); 

    holder.name.setText(mUserBrand.getName().toString()); 



    holder.btnadd.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      if(holder.btnadd.getText().toString() == "ADD"){ 

       holder.btnadd.setText("ADDED"); 
       notifyDataSetChanged(); 

      } 





     } 
    }); 

    return v; 
} 

當我點擊按鈕文本沒有改變對那個位置該特定項目的按鈕。

如何更改特定位置上的特定項目按鈕上的按鈕文本?

+0

如果在單擊監聽器中使用'((Button)v)'而不是'holder.btnadd'?因爲'holder.btnadd'發生了變化,但是''v''在'onClick'內是正確的視圖。 –

+0

我沒有得到它。你能詳細解釋一下嗎? – deepak

+0

添加它作爲答案。 –

回答

2

我認爲你應該像這樣更新你的OnClick: 使用.equals比較字符串,否則你是比較對象。

使用Button btnadd = (Button)v;確保您使用的是單擊的視圖,該視圖作爲參數提供給onClick函數,因此總是您期望的。

holder.btnadd.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     Button btnadd = (Button)v; 
     if(btnadd.getText().toString().equals("ADD")){ 
      btnfollow.setText("ADDED"); 
      notifyDataSetChanged(); 
     } 
    } 
}); 
+0

.equals或.equalsignoreCase? –

+0

它工作完美。你能解釋更多關於使用Button btnadd =(Button)v;'? – deepak

+1

這取決於你想要什麼,我認爲平等應該在這裏工作,如果你不希望檢查是區分大小寫的,你可以使用equalsIgnoreCase。 –

相關問題