android编程之代码布局(三)

前两篇介绍了一般常用的布局组件写法,这一次,再来看看其他组件的

一、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);

				// head
				ImageView 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);

				// nickname
				TextView 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中读取得到的,头像的也是。

最后附上显示效果:
android编程之代码布局(三)_第1张图片

你可能感兴趣的:(编程,android,object,ListView,null,Class)