2017-04-01 46 views
-1

我有一個應該包含圖像按鈕的自定義適配器。但是,我對getView()方法的覆蓋實現感到困惑。由於我的圖像按鈕是動態定義的,我能夠通過使用代碼如何動態定義項目時創建自定義陣列適配器

@Override 
public View getView(int i, View view, ViewGroup viewGroup){ 
    ImageButton ibutton = (ImageButton) getItem(i); 

如何返回其以恢復圖像按鈕?我沒有專門爲它創建一個xml文件,因爲它只是一個ImageButton(不與其他任何組合),但它是否有必要爲它創建一個xml?或者有沒有辦法輕鬆從圖像按鈕本身獲取視圖。

當我嘗試使用getView()時,出於某種原因,imagebutton不可點擊。

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageButton imageButton = getItem(position); 
    return imageButton ; 
} 

回答

1

試圖建立你適配器是這樣的:

public class ImageButtonAdapter extends BaseAdapter { 
    private Context mContext; 

    // Constructor 
    public ImageButtonAdapter(Context c) { 
     mContext = c; 
    } 

    public int getCount() { 
     return listCount; 
    } 

    public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

    // create a new ImageButton for each item referenced by the Adapter 
    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageButton imageButton ; 

     if (convertView == null) { 
     imageButton = new ImageButton (mContext); 
     imageButton.setLayoutParams(lp); 
     } 
     else 
     { 
     imageButton = (ImageButton) convertView; 
     } 
     imageButton.setBackgroundColor(Color.TRANSPARENT) 
     return imageButton ; 
    } 

} 
+0

謝謝,這個作品。我不知道ImageButton本身可以作爲視圖返回。 – kmindspark

+0

對不起,實際上,當我嘗試使用getView方法時,imagebuttons由於某種原因沒有顯示出來。你知道爲什麼嗎? (我現在註釋了佈局參數線)我更新了原始問題,還有另一個問題,即圖像按鈕不能被點擊。 – kmindspark

+1

您是否嘗試在圖像按鈕上設置clickListener,如下所示:imageButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Log.e(「position」,「position」 + position); } }); –