布局学习3之代码布局2
接着上面代码学习
我们把l1背景颜色改成红色:
l1.setBackgroundColor(Color.RED);
其实setContenView
添加一个:
LinearLayout.LayoutParamsll2=newLinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
可以改成addContentView(l1, ll2)
运行后的效果是:
我们发现两者方法的作用都是一样的,都是添加显示的内容。但是有一些细微的差别,setContentView的方法有三种可以按照,添加布局的方法,显示view。比如setContentView(R.layou.id).也可以直接显示View,比如setContentView(View),当然可以setContentView(View,LayoutParams).而addConetntView也是显示view,但是方法只有一种addContentView(View,LayoutParams).下面再主要是讲应用addView方法。
在这里我们定义了一个画图的类继承view。View1类,主要是画一个圆形。
publicclass View1extends View{
public View1(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
publicvoid draw(Canvascanvas) {
// TODO Auto-generated method stub
super.draw(canvas);
Paintp= new Paint();
p.setColor(Color.RED);
canvas.drawCircle(50,50,20, p);
}
}
java代码:布局代码
publicclassCodeLayoutActivityextends Activity{
/** Called when the activity isfirst created. */
View1view1;
@Override
publicvoid onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l1 =new LinearLayout(this);
view1 =new View1(this);
l1.setLayoutParams(newLayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
l1.setOrientation(LinearLayout.VERTICAL);
//l1.setBackgroundColor(Color.RED);
Button b1 =new Button(this);
b1.setText("Ok");
LinearLayout.LayoutParams ll1 =new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams ll2 =new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
ll1.topMargin= 50;
ll1.leftMargin = 100;
l1.addView(view1);
//l1.addView(b1,ll1);
addContentView(l1, ll2);
}
}
运行结果:
我们通过addview方法来增加了view再linearlayout(l1)中。addView方法只是在view增加view,不是拿来直接显示在屏幕上,作用是把view添加到view中比如button,seekbar等。直接显示屏幕上需要用addContentView何setContentView方法。
代码下载请:
http://download.csdn.net/detail/tianke0711/4673456
未完待续,请耐心等待!