开发者

How to make a android ListView with a ImageView and TextView in Each Line? [duplicate]

开发者 https://www.devze.com 2023-04-09 23:46 出处:网络
This question already has answers here: 开发者_如何学运维 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_如何学运维 Closed 11 years ago.

Possible Duplicate:

Can I have a List view and images icon with textview on the Android

How to make a android ListView with a ImageView and TextView in Each Line?

I am working on a Android app that is going to have a screen with a ListView on it and its going to need a ImageView and a TextView on each line... can someone please help me out with some clues and samples


You will need to teach your ListAdapter how to do that. This may be by subclassing it and overriding getView(), if this is an ArrayAdapter. You can design your own custom rows and use those, pouring in the data for the ImageView and TextView as the rows get loaded.

Here is a free excerpt from one of my books that goes through the process. Here is the source code to the sample projects profiled in that chapter.


As mentioned, you will need to extend an adapter and use it in your ListActivity. Make an XML file with a TextView and an ImageView (using LinearLayout or any other layout). You can add IDs to TextView and ImageView so you can change them according to the position in the list.

Here is a code example that creates three rows and sets the text in them to a, b, c.

public class MyActivity extends ListActivity {

    private String[] data = {"a","b","c"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new MyAdapter(this, R.layout.rowxml, data));
    }

    private class MyAdapter extends ArrayAdapter<String> {

        public MyAdapter(Context c, int i, String[] s) {
            super(c, i, s);
        }

        @Override
        public View getView(int position, View v, ViewGroup parent) {
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.rowxml, null);
            }

            TextView tw = (TextView) v.findViewById(R.id.text);
            if (tw != null) tw.setText(data[position]);

            // You can do something similar with the ImageView  

            return v;
        }
    }
}


In short, you should use a ListActivity. You'll be able to set the layout xml for each row.

Take a look at this tutorial:

What you need to do is the same, but adapt it to have an ImageView in addition to a textview.

0

精彩评论

暂无评论...
验证码 换一张
取 消