如何在Android中的ListView中的文本项旁边添加图像? [英] How do add images next to text Items in ListView in Android?
本文介绍了如何在Android中的ListView中的文本项旁边添加图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在ListView中的每个项目旁边添加一个图像,但到目前为止没有任何成功. 有一个数据库,我可以从中检索文本数据,如下所示:
I am trying to add an image next to each item in my ListView but without any success so far. There is a DB, from where I retrieve the text data, like this:
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
Then I create an array to store the image IDs
Integer[] imageIds = new Integer[]{
R.drawable.cat1,
R.drawable.cat2,
R.drawable.cat3,
};
我不知道是如何将它们绑定在一起的.非常感谢您的帮助!
What I cannot figure out is how to bind them together. Thanks a lot for the help!
推荐答案
首先创建一个数据模型:
First make a data model :
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;
}
}
然后创建一个自定义适配器:
then make a custom adapter :
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;
}
}
在您的活动中执行此操作:
in your activity do this:
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));
这篇关于如何在Android中的ListView中的文本项旁边添加图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文