Proper usage of twoLineListItem Android

前端 未结 3 968
误落风尘
误落风尘 2021-01-07 02:44

I am new to development on android and trying to create a list that has a bold header
and a smaller description for each item. Like the one shown here (sorry can\'t post

3条回答
  •  旧时难觅i
    2021-01-07 03:08

    In the case of an Array of Objects, you just have to implement your own adapter. It can work for a TwoLineListItem or any other custom layout.

    For example, if I have a list of items of the following type :

    public class ProfileItem {
        public String host, name, tag;
    
        public ProfileItem(String host, String name, String tag) {
            this.host = host;
            this.name = name;
            this.tag = tag;
        }
    
        @Override
        public String toString() {
            return name+"#"+tag;
        }
    }
    

    Then I create the following adapter :

    public class ProfileItemAdapter extends ArrayAdapter {
    
    private Context context;
    private int layoutResourceId;   
    private List objects = null;
    
    public ProfileItemAdapter(Context context, int layoutResourceId, List objects) {
        super(context, layoutResourceId, objects);
        this.context = context;
        this.layoutResourceId = layoutResourceId;
        this.objects = objects;
    }
    
    public View getView(int position, View convertView, ViewGroup parent)  {
        View v = convertView;
        if(v == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            v = inflater.inflate(layoutResourceId, parent, false);
        }
    
        ProfileItem item = objects.get(position);
        TextView titletext = (TextView)v.findViewById(android.R.id.text1);
        titletext.setText(item.toString());
        TextView mainsmalltext = (TextView)v.findViewById(android.R.id.text2);
        mainsmalltext.setText(item.host);
        return v;
    }
    

    }

    Then everything is in place, in my activity (or fragment), I just have to set this adapter in the onCreate method :

    setListAdapter(new ProfileItemAdapter(getActivity(),
                android.R.layout.two_line_list_item, // or my own custom layout 
                ProfileListContent.ITEMS));
    

提交回复
热议问题