android 不使用布局文件,完全由代码控制布局实例

前言

我们先来看一下实现效果:


实现

MainActivity.java

package cn.sehzh.tester;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
	private LinearLayout mLayout;
	private TextView mTextView1, mTextView2, mTextView3, mTextView4;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		init();
		setContentView(mLayout);
	}

	private void init() {
		LayoutParams params, tvParams;

		mLayout = new LinearLayout(this);
		params = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
		mLayout.setLayoutParams(params);
		mLayout.setOrientation(LinearLayout.VERTICAL);

		// 获得屏幕宽度
		Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
		int height = display.getHeight();

		mTextView1 = new TextView(this);
		mTextView1.setHeight(height / 4);
		mTextView1.setBackgroundColor(Color.GRAY);
		mTextView1.setText("first textview");

		mTextView2 = new TextView(this);
		mTextView2.setHeight(height / 4);
		mTextView2.setBackgroundColor(Color.RED);
		mTextView2.setText("second textview");

		mTextView3 = new TextView(this);
		mTextView3.setHeight(height / 4);
		mTextView3.setBackgroundColor(Color.GREEN);
		mTextView3.setText("third textview");

		mTextView4 = new TextView(this);
		mTextView4.setHeight(height / 4);
		mTextView4.setBackgroundColor(Color.BLUE);
		mTextView4.setText("fourth textview");

		tvParams = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		mLayout.addView(mTextView1, tvParams);
		mLayout.addView(mTextView2, tvParams);
		mLayout.addView(mTextView3, tvParams);
		mLayout.addView(mTextView4, tvParams);

		// 设置全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值