通过编码方式实现软件的布局

程序运行结果图示:

通过编码方式实现软件的布局_第1张图片


需要注意的是:

1)一个控件只能有一个父元素,如果多次添加
09-02 11:01:34.785: E/AndroidRuntime(23954):
 java.lang.RuntimeException: Unable to start activity ComponentInfo{cn.itcast.codeui/cn.itcast.codeui.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

1、把新建项目时的main.xml文件删除


2、MainActivity

package com.njupt.codeui;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); 
		LayoutParams params1 = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
		LayoutParams params2 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		
		LinearLayout linearLayout = new LinearLayout(this);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		
		TextView tv = new TextView(this);
		tv.setText("请输入你的老婆的姓名");
		linearLayout.addView(tv,params1);
		
		EditText et = new EditText(this);
		et.setText("章泽天");
		linearLayout.addView(et,params1);
		
		Button bt = new Button(this);
		bt.setText("确定");
		linearLayout.addView(bt,params2);
		
		setContentView(linearLayout,params);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


你可能感兴趣的:(通过编码方式实现软件的布局)