2016-05-07 44 views
0

我想在我的ListView中的每個項目旁邊添加一個圖像,但目前爲止沒有任何成功。 有一個數據庫,從那裏我檢索文本數據,就像這樣:如何在Android中的ListView中的文本項旁邊添加圖像?

Cursor categoriesCursor = myCategoryData.getCategoriesData(); 

    String[] displayCategories = new String[]{ CategoryDataSource.NAME}; 
    int[] displayViews = new int[]{R.id.list_name}; 


    setListAdapter(new SimpleCursorAdapter(
      this, 
      R.layout.list_category, 
      categoriesCursor, 
      displayCategories, 
      displayViews,1)); 

    myListView = getListView(); 

然後,我創建一個數組存儲圖像的ID

Integer[] imageIds = new Integer[]{ 
       R.drawable.cat1, 
       R.drawable.cat2, 
       R.drawable.cat3, 
     }; 

我想不通的是如何綁定他們在一起。非常感謝您的幫助!

+1

創建自定義適配器,檢查[此](https://github.com/mohit008/Android-List-View) – Mohit

回答

1

首先製作一個數據模型:

public class dataModel { 
String title; 
int imageId; 

public dataModel(String title, int imageId) { 
    this.title = title; 
    this.imageId = imageId; 
} 

public String getTitle() { 
    return title; 
} 

public void setTitle(String title) { 
    this.title = title; 
} 

public int getImageId() { 
    return imageId; 
} 

public void setImageId(int imageId) { 
    this.imageId = imageId; 
} 
} 

然後進行自定義適配器:

public class adapter extends BaseAdapter{ 
ArrayList<dataModel> allItems=new ArrayList<>(); 
Context mContext; 
public adapter(Context ct, ArrayList<dataModel> allItems) { 
    this.allItems = allItems; 
    mContext=ct; 
} 

@Override 
public int getCount() { 
    return allItems.size(); 
} 

@Override 
public Object getItem(int position) { 
    return allItems.get(position); 
} 

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

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    // YOU SHOULD INFLATE A VIEW HERE 
    View mView=View.inflate(mContext,R.id.YOUR_VIEW_ID,null); 
    TextView mText= .... ; 
    ImageView mImage= ... ; 

    dataModel mModel=(dataModel) getItem(position); 
    mText.setText(mModel.getTitle()); 
    mImage.setImageResource(mModel.getImageId()); 

    return mView; 
} 
} 

您的活動做這樣的:

String[] displayCategories = new String[]{ CategoryDataSource.NAME}; 
int[] displayViews = new int[]{R.id.list_name}; 

// make an array list of dataModel Items 
ArrayList<dataModel> data=new ArrayList<dataModel>(); 
for(int i=0;i<displayCategories.length;i++){ 
    data.add(new dataModel(displayCategories[i],displayViews[i])); 
} 

setListAdapter(new adapter(this,data)); 
相關問題