简体   繁体   中英

What's the best way to use Adapters on Android?

What's the best way to use Adapters on Android? We can use it for several customized operations. By using the adapter we will include some pre-implemented methods. When should I use these methods? How can we improve our apps' performance by using the Adapter implemented methods?

public int getCount() {
        // TODO Auto-generated method stub
        return country.length;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
}

Look out this sample example and the link

public class GridDemo extends Activity implements AdapterView.OnItemClickListener {
    private TextView selection;
    private static final String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"};

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        selection=(TextView)findViewById(R.id.selection);
        GridView g=(GridView) findViewById(R.id.grid);
        g.setAdapter(new ArrayAdapter<String>(this, R.layout.cell, items));
        g.setOnItemClickListener(this);
    }

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        selection.setText(items[position]);
    }
}

You can get an idea for this Adapters..

BaseAdapter is a great choice for simply using ListView or GridView . But if you want to get data from the database, a CursorAdapter is much more well suited for that, though the doc says this is for ListView . So a SimpleCursorAdapter would be the other type you'd use if you want both ListView and GridView usage when pertaining to showing data you get from a database. But of course knowing your implementation would help me better give you the best choice.

I should also add since I saw it on one of the comments, ArrayAdapter is basically a BaseAdapter , but the difference being it takes arrays of arbitrary objects aka best suited for arrays straight out of the box.

getCount() is a must. It tells ListView, GridView or etc that how many items to display. getItem() and getItemId() in many cases (if you implement getView() by your own code) are actually optional, they are just helper methods. There methods are basic to an adapter, it doesn't help on performance improvement. I think getView()'s implementation effect performance the most.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM