2013-02-05 83 views
0

我有一個ListActivity和在我的列表中我有非常複雜的listitems與多個ImagesViews TextViews和按鈕。當我點擊一個按鈕時,我想編輯一些textviews並改變一些背景顏色。我的實現工作,但只有當我點擊的按鈕是在第一行可見。我使用getChildAt()來抓取其中一個可見的行,但我需要知道要抓取哪一行。如何知道android列表中的哪一行按下按鈕?

public void onClick(View v){ 
    System.out.println("Something got clicked"); 
    if(v.getId() == R.id.lovebutton){ 
     MainListItem i = mainAdapter.getItem(listView.getFirstVisiblePosition()); 
      i.loved=true; 
      i.loves++; 
      View view; 
       view = listView.getChildAt(0); 
       //view = listView.getChildAt(1); 
      ((TextView) view.findViewById(R.id.lovecount)).setText(String.valueOf(i.loves)); 
      view.findViewById(R.id.lovebutton).setBackgroundColor(Color.parseColor(i.brandLoveColor)); 
      ((ImageView)view.findViewById(R.id.lovebutton)).setImageResource(R.drawable.lovewhite); 
     }} 
+0

你爲什麼不使用BaseAdapter和分別處理每個視圖....? –

+0

ArrayAdapter和BaseAdapter有什麼區別?我目前使用ArrayAdapter – mpatten

+0

是ListView的按鈕部分嗎? –

回答

2

有很多方法可以做到這一點。保存pojo中的狀態,在onClick中更新它們並呼叫#notifyDataSetChanged()。 或者, 您可以將位置作爲標籤添加到適配器的getView中的按鈕上。在OnClick中,您可以獲取標籤。這樣你就會知道按鈕屬於哪個位置。

從喬的幫助不大 - Android: Access child views from a ListView

public void onClick(View v){ 
    System.out.println("Something got clicked"); 
    if(v.getId() == R.id.lovebutton){ 
     int wantedPosition = Integer.parseInt(view.getTag()); 
     int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0 
     int wantedChild = wantedPosition - firstPosition; 
     // Say, first visible position is 8, you want position 10, wantedChild will now be 2 
     // So that means your view is child #2 in the ViewGroup: 
     if (wantedChild < 0 || wantedChild >= listView.getChildCount()) { 
      Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen."); 
      return; 
     } 
     // Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead. 
     View wantedView = listView.getChildAt(wantedChild); 
     MainListItem i = mainAdapter.getItem(wantedPosition); 
     i.loved=true; 
     i.loves++; 
     ((TextView) view.findViewById(R.id.lovecount)).setText(String.valueOf(i.loves)); 
     view.findViewById(R.id.lovebutton).setBackgroundColor(Color.parseColor(i.brandLoveColor)); 
     ((ImageView)view.findViewById(R.id.lovebutton)).setImageResource(R.drawable.lovewhite); 
    } 
} 
+0

謝謝我最終在按鈕上使用了'setTag()',它的工作方式就像一個魅力! – mpatten

1

在listView中得到點擊行,你必須使用「OnItemClickListener」。

lv.setOnItemClickListener(new OnItemClickListener() { 

        @Override 
        public void onItemClick(AdapterView<?> arg0, View arg1, 
          int pos, long arg3) { 
         HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(pos);  
          System.out.println(pos);//This will return your position 

        } 
       }); 
相關問題