前兩篇介紹了一般常用的布局組件寫法,這一次,再來看看其他組件的
一、listview
listview也和大多數組件一樣,一般會在這裡難住的,就是自訂配置樣式的時候。
// 建立LinearLayout對象LinearLayout mRelativeLayout = new LinearLayout(this);mRelativeLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));// 建立ListView對象ListView mListView = new ListView(this);mListView.setAdapter(new ListAdapter(this, mVector));// 添加組件mRelativeLayout.addView(mListView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
其中,ListAdapter為繼承BaseAdapter的自訂類。
mVector是我們自訂的資料,裡麵包含了兩個名字:小明,小剛。
接下來,我們看看重點的ListAdapter是如何自訂布局的
public class ListAdapter extends BaseAdapter {private Vector<String> mVector;private Context mContext;public ListAdapter(Context mContext, Vector<String> mVector) {this.mContext = mContext;this.mVector = mVector;}public Object getItem(int position) {return null;}public long getItemId(int position) {return 0;}public int getCount() {return mVector.size();}class ViewHolder {ImageView head;TextView name;}public View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder = null;RelativeLayout rl = null;if (convertView == null) {rl = new RelativeLayout(mContext);rl.setBackgroundDrawable(bitmapDrawable_listitembg);// headImageView head = new ImageView(mContext);head.setId(1);RelativeLayout.LayoutParams mLayoutParams = new RelativeLayout.LayoutParams(64, 64);mLayoutParams.topMargin = 15;mLayoutParams.leftMargin = 10;mLayoutParams.bottomMargin = 15;mLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL);rl.addView(head, mLayoutParams);// nicknameTextView mTextView = new TextView(mContext);mTextView.setTextSize(20);mTextView.setTextColor(0xff000000);mTextView.setId(2);mLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);mLayoutParams.topMargin = 10;mLayoutParams.leftMargin = 10;mLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);rl.addView(mTextView, mLayoutParams);holder = new ViewHolder();holder.head = head;holder.name = mTextView;rl.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();rl = (RelativeLayout) convertView;}holder.head.setImageDrawable(bitmapDrawable_headimage);holder.name.setText(mVector.elementAt(position));return rl;}}
如果對之前講的相對布局看過的話,這裡對自訂布局的寫法應該不難理解。
定義了一個頭像ImageView和一個名字TextView。讓頭像距離上下左各有一段距離,然後讓名字在頭像右邊顯示,並距離頭像右一定距離。
關於布局背景圖片的設定:rl.setBackgroundDrawable(bitmapDrawable_listitembg);設定的圖片是從asset中讀取得到的,頭像的也是。
最後附上顯示效果: