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

前言

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

android 不使用布局文件,完全由代码控制布局实例_第1张图片

实现

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);

	}

}


你可能感兴趣的:(Android,Android开发,android,代码,布局)