如何使用ListView插入图像?

时间:2015-02-28 18:03:16

标签: android listview

我需要修改我的代码,使其显示带有图像的文本,而不是将整个代码更改为具有图像功能的另一个代码:

这是我的图片代码:

 int[] imgs = new int[]
    {
        R.drawable.wifi,
        R.drawable.bluetooth,
        R.drawable.usb,
        R.drawable.cloud,
        R.drawable.remote,

    };

这是我的ListView代码:

listView = (ListView) findViewById(R.id.operations);
listView.setTextFilterEnabled(true);
String[] values = new String[]
        {"Nearby Wifi",
         "Nearby Blutooth",
         "Direct USB Connected",
         "Google Cloud Print",
         "Printer Remote"
        };

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        R.layout.custom_listview, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {


        int itemPosition = position;

        String itemValue = (String)   listView.getItemAtPosition(position);

        //if condition
    }


});

这是我的custom_listview

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:paddingTop="2dip"
android:paddingBottom="3dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textColor="@android:color/black"
android:textStyle="bold"
  />

如何修改它以显示带有图像的文字?

2 个答案:

答案 0 :(得分:0)

您需要自定义列表视图

  1. 自定义列表视图行xml(Imageview&amp; Textview)
  2. 自定义基准适配器
  3. 点击此链接, http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=9

答案 1 :(得分:0)

返回适配器的视图是TextView。你能做的就是用 setCompoundDrawables

实施例:     编辑:     ...

    listView.setAdapter(new BaseAdapter() {
        @Override
        public int getCount() {
            return values.size();
        }

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            if(convertView == null) {
                convertView = inflater.inflate(R.layout.custom_textview);

                TextView tv = (TextView) convertView.findViewById(R.id.text1);
                tv.setCompoundDrawables(getResources().getDrawable(imgs[position]), null, null, null);
tv.setText(values.get(position));
            }

            return convertView;
        }
    });