如何在Android中的ListView中的文本项旁边添加图像?

时间:2016-05-07 05:18:29

标签: android image listview text

我正在尝试在ListView中的每个项目旁边添加图像,但到目前为止没有任何成功。 有一个数据库,我从中检索文本数据,如下所示:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}

然后我创建一个数组来存储图像ID

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();

我无法弄清楚如何将它们绑在一起。非常感谢您的帮助!

1 个答案:

答案 0 :(得分: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));