android 自定义ListView加自己的布局
2015-10-15 · 知道合伙人软件行家
Listview使用自定义布局,则需要创建layout,并引用layout。以下为示例代码:
创建layout文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/online_user_list_item_textview" android:text="TextView"></TextView>
<Button
android:text="button"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
2.layout面含有的textview是想要展示内容的地方。那么构建ArrayAdapter时,应该这样写:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.online_user_list_item, R.id.online_user_list_item_textview);
3.ArrayAdapter并且重写getView方法。代码:
public class UserListAdapter extends ArrayAdapter<User> {
private int resourceId;
public UserListAdapter(Context context, int textViewResourceId, List<User> objects) {
super(context, textViewResourceId, objects);
this.resourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
User user = getItem(position);
LinearLayout userListItem = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resourceId, userListItem, true);
TextView tvUsername = (TextView)userListItem.findViewById(R.id.tv_user_list_username);
TextView tvAskedNum = (TextView)userListItem.findViewById(R.id.tv_user_list_askednum);
TextView tvLastMsg = (TextView)userListItem.findViewById(R.id.tv_user_list_lastmsg);
tvUsername.setText(user.getUsername());
tvAskedNum.setText(String.valueOf(user.getAskedNum()));
tvLastMsg.setText(user.getLastMsg());
return userListItem;
}
}
4.将适配器应用到ListView即可,listview.setAdapter(arrayAdapter);即可实现。