java代码创建Android界面
来源:移动互联培训 2017-02-081. View的属性分两类,
(1)第 一是View本身的属性:前缀没有"layout_"
(2)第二是View因为容器而具有的属性:前缀有"layout_"
2.布局文件中使用属性示例
3. Java代码中属性示例(包括操作UI本身属性与来自于布局UI的属性)
下面的代码全部是使用java代码来做的界面,但是可以达到与上面使用布局文件同样的效果(在eclips自还模式器中测试成功)
public class MainActivity extends Activity {
public View getView() {
LinearLayout out1 = new LinearLayout(this);
LinearLayout out2 = new LinearLayout(this);
ImageView imageView = new ImageView(this);
EditText editText = new EditText(this);
Button button = new Button(this);
out1.addView(out2);
out1.addView(button);
out2.addView(imageView);
out2.addView(editText);
LinearLayout.LayoutParams p1
= new LinearLayout.LayoutParams(0, 0);
p1.width = p1.MATCH_PARENT;
p1.height = p1.MATCH_PARENT;
p1.weight = 1;
out1.setLayoutParams(p1);
out1.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(0,0);
p2.width = p2.MATCH_PARENT;
p2.height = p2.MATCH_PARENT;
p2.weight = 1;
out2.setLayoutParams(p2);
out2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams p3 = new LinearLayout.LayoutParams(0,0);
p3.width = p3.MATCH_PARENT;
p3.height = p3.MATCH_PARENT;
p3.weight = 1;
button.setLayoutParams(p3);
button.setText("确定");
LinearLayout.LayoutParams p4 = new LinearLayout.LayoutParams(0,0);
p4.width = 100;
p4.height = p4.MATCH_PARENT;
p4.gravity = Gravity.LEFT|Gravity.CENTER_VERTICAL;
imageView.setLayoutParams(p4);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(R.drawable.ic_launcher);
LinearLayout.LayoutParams p5 = new LinearLayout.LayoutParams(0,0);
p5.width = p5.MATCH_PARENT;
p5.height = p5.MATCH_PARENT;
p5.gravity = Gravity.RIGHT;
editText.setLayoutParams(p5);
editText.setBackgroundColor(0xff00ff00);
editText.setText("请输入名字");
editText.setTextSize(50.0f);
return out1;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(this.getView());
}
}
Copyright ©2004-2018 华清远见教育科技集团 版权所有
京ICP备16055225号,京公海网安备11010802025203号