如這篇文章:http://www.linuxidc.com/Linux/2012-01/50686.htm
我們進行了SimpleAdapter適配器初次嘗試,那麼離實現我們最終想要的效果也不遠啦,只要仿照chata的布局,再編寫第二位聊天人(“路人甲”)的布局chatb——只要讓他靠右顯示就行~。
但是這樣我們每次都要很麻煩的定義一遍SimpleAdapter,為了“偷懶”,我們直接來編寫自己的Adapter,這樣每次定義就方便多了。
先附上最終的代碼:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- chatlist = (ListView) findViewById(R.id.chatlist);
- list = new ArrayList<ChatEntity>();
- ChatEntity chat1=new ChatEntity("小魏","嗨~",R.layout.chata);
- list.add(chat1);
- ChatEntity chat2=new ChatEntity("路人甲","你好!",R.layout.chatb);
- list.add(chat2);
- ChatEntity chat3=new ChatEntity("小魏","我是小魏~",R.layout.chata);
- list.add(chat3);
-
- chatlist.setAdapter(new ChatAdapter(TryChatPop2Activity.this,list));
- }
如上代碼,在setAdapter時使用了自己的ChatAdapter,以下是類文件代碼:
- public class ChatAdapter implements ListAdapter{
- private ArrayList<ChatEntity> list;
- private Context ctx;
-
- public ChatAdapter(Context context ,ArrayList<ChatEntity> list) {
- ctx = context;
- this.list = list;
- }
-
- public boolean areAllItemsEnabled() {
- return false;
- }
- public boolean isEnabled(int arg0) {
- return false;
- }
- public int getCount() {
- return list.size();
- }
- public Object getItem(int position) {
- return list.get(position);
- }
- public long getItemId(int position) {
- return position;
- }
- public int getItemViewType(int position) {
- return position;
- }
- public View getView(int position, View convertView, ViewGroup parent) {
- ChatEntity entity = list.get(position);
- int itemLayout = entity.getLayoutID();
-
- LinearLayout layout = new LinearLayout(ctx);
- LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- vi.inflate(itemLayout, layout,true);
-
- TextView txvName = (TextView) layout.findViewById(R.id.txvName);
- txvName.setText(entity.getName());
-
- TextView txvText = (TextView) layout.findViewById(R.id.txvInfo);
- txvText.setText(entity.getInfo());
- return layout;
- }
- public int getViewTypeCount() {
- return list.size();
- }
- public boolean hasStableIds() {
- return false;
- }
- public boolean isEmpty() {
- return false;
- }
- public void registerDataSetObserver(DataSetObserver observer) {
- }
- public void unregisterDataSetObserver(DataSetObserver observer) {
- }
-
- }