来自drawable文件夹的单列图像列表,仅使用XML

时间:2015-08-09 22:32:29

标签: android xml listview xml-drawable

是否可以创建存储在drawable文件夹中的图像的滚动列表视图,仅使用XML?

之前,我在我的XML中有一个ListView,每个drawable都在自己的ImageView中。我在Java中找到了使用适配器和类的解决方案,但是只有XML解决方案吗?

我已经构建了这个字符串数组,其中" picture1.png"是我的drawable文件夹中的一个图像。

<string-array name="mylistofpictures">
    <item>picture1</item>
    <item>picture2</item>
    <item>picture3</item>
    ...
    <item>picture99</item>
</string-array>

2 个答案:

答案 0 :(得分:0)

string-array中创建string.xml并在适配器类中找到它。

public class MainActivity extends Activity {
 ListView list;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
        list.setAdapter(new MyAdapter(this));
 }

 public class MyAdapter extends BaseAdapter{

    private String [] image;
    private Context context;

    public  MyAdapter(Context context){
        this.context = context;

        //-- here you are getting array from xml
        image= getResources().getStringArray(R.array.array);  
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup   parent) {
        imageView.setBackgroundResource(getResources().getIdentifier(image[position], "drawable", getPackageName()));
        return view;
        }
  }
}

答案 1 :(得分:0)

如果你想只使用xml。从R文件中获取可绘制的ID,并将其作为值包含在xml列表或具有匹配索引的其他xml列表中。使用与listview项相同的索引设置drawableid,并使用setDrawable使用id设置图像。

相关问题