以编程方式创建用户界面

作者:追风剑情 发布于:2015-7-26 12:08 分类:Android

使用代码创建用户界面是一个非常费力的工作。因此,只有在必要时才使用代码来动态生成用户界面。

package com.example.androidtest;

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

public class UICodeActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_uicode);//必须注释掉
		LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		
		TextView tv = new TextView(this);
		tv.setText("This is a TextView");
		tv.setLayoutParams(params);
		
		Button btn = new Button(this);
		btn.setText("This is a Button");
		btn.setLayoutParams(params);
		
		layout.addView(tv);
		layout.addView(btn);
		
		LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		
		this.addContentView(layout, layoutParam);
	}
}

运行效果

11111111111.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号