How to create list with different elements and act

2019-04-10 09:12发布

问题:

I want to create list with different types of items. They should call different intents or do other things (display a map etc.) . It should act like contact details. Numbers of items and actions is predefined.

How to achieve this effect elegantly? I don't need exact code but guidelines and information where to look. Any help will be appreciated :)


UPDATE:

By "this effect" I mean creating a list of different types of items (onClickListener, layout). On picture above you can see that you have a contact with various options: calling somebody, emailing, chatting, looking at google maps etc. All of those options are grouped at list.

I'm wondering if it could be achieved by xml layout without defining custom Adapter class. I want also be able to add some static header rows with eg. category name.

回答1:

The only way I see to achieve this would be to indeed create a custom adapter class. I'm using this to create a file browsers, with different actions based on wether the item selected is a file or a folder.

Basically, You need to create a custom adapter extending ArrayAdapter (you can use another base class if all your items inherit from the same class). Here's a sample code :

public class MyCustomAdapter extends ArrayAdapter<Object> {


    public MyCustomAdapter(Context context, int textViewResourceId,
            ArrayList<Object> objects) {
        super(context, textViewResourceId, objects);
        mList = objects;
    }


    public View getView(int position, View convertView, ViewGroup parent) {
        Object obj = mList.get(position);
        View v = convertView;
        LayoutInflater vi = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        if (obj.getClass().isAssignableFrom(MyClass1.class)){
            v = vi.inflate(R.layout.myclass1_item_layout, null);
            setupViewClass1(obj,v);
        } else if (obj.getClass().isAssignableFrom(MyClass2.class)){
            v = vi.inflate(R.layout.myclass2_item_layout, null);
            setupViewClass2(obj,v);
        }

        return v;
    }

    private void setupViewClass1 (Object obj, View v){  
        // setup the content of your view (labels, images, ...)
    }

    private void setupViewClass2 (Object obj, View v){  
        // setup the content of your view (labels, images, ...)
    }

    private ArrayList<Object> mList;

}

Then you need to add an OnItemClickListener as well as an OnCreateContextMenuListener to handle the click and longpress event on your list, again making a filter on the class of your object.