前言

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

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;@Overrideprotected 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);}}


更多相关文章

  1. android控件相对布局
  2. Android 动态布局
  3. 00015-相对布局位置属性
  4. Android中的集中常用布局方式和按钮事件的处理方式
  5. android RelativeLayout(相对布局)详细说明
  6. 如何通过代码更改ANDROID的UI布局
  7. Android之布局属性
  8. Android开发之ConstraintLayout布局
  9. android布局学习利器-Hierarchy Viewer

随机推荐

  1. 准大学生,如何预习计算机专业?
  2. 这道算法题用「动态规划」求解可麻烦了!
  3. 新手如何有效的刷算法题(LeetCode)
  4. 转:基于 Android(安卓)NDK 的学习之旅----
  5. 讲道理,MD5 到底是不是加密算法?
  6. 神器面世:快速生成你的专属卡通头像!
  7. 一个有意思的分钱模拟问题
  8. 如何设计一个支持增量操作的栈
  9. Markdown 必备神器
  10. 《Python知识手册》,V3.0版来了,2021年,走起