使用字符串更改ImageView Android:src

时间:2016-10-03 18:42:45

标签: android

我有一个正在返回的字符串,它是xml布局文件中出现的图像的位置,因此“@ drawable / image”。

我的问题是可以在代码中更改android:src =“@ drawable / image”中的字符串吗?

编辑:

        <ImageView
        android:id="@+id/imageuni"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:src="@drawable/no_image"/> <!--Change this part in code-->

我正在使用带有CustomBinder的SimpleAdapter:

        SimpleAdapter adapter = new SimpleAdapter( SearchActivity.this,leaderList, R.layout.search_entry, new String[] {
                "rankId","name","location","image"}, new int[] {R.id.rankId,R.id.name,R.id.location,R.id.imageuni});
        adapter.setViewBinder(new CustomViewBinder());
        setListAdapter(adapter);

活页夹代码:

class CustomViewBinder implements SimpleAdapter.ViewBinder {
    public boolean setViewValue(View view, Object inputData, String textRepresentation) {
    int id = view.getId();
    String data = (String) inputData;
    switch (id) {
        case R.id.imageuni:
            populateImage(view, data);
            break;

        case R.id.location:
            populateLocation(view, data);
            break;

        case R.id.name:
            populateName(view, data);
            break;

    }
    return true;
}
public void populateImage(View view, String imageData) {
    ImageView uniImage = (ImageView) view.findViewById(R.id.imageuni);
    uniImage.setImageDrawable(Drawable.createFromPath(imageData));
}

public void populateLocation(View view, String data) {
    TextView locationTxt = (TextView) view.findViewById(R.id.location);
    locationTxt.setText(data);
}

public void populateName(View view, String data) {
    TextView dateTxt = (TextView) view.findViewById(R.id.name);
    dateTxt.setText(data);
}

}

我获取行项的ID并构建一个字符串以获取图像的名称,例如第一个图像名为u1.jpg,它位于我的drawable res文件夹中。

1 个答案:

答案 0 :(得分:0)

你在找这个吗?

ImageView img = (ImageView) findViewById(R.id.img);
img.setImageResource(R.drawable.u1);