android 不使用布局文件,完全由代码控制布局实例
16lz
2021-01-23
前言
我们先来看一下实现效果:
实现
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);}}
更多相关文章
- android控件相对布局
- Android 动态布局
- 00015-相对布局位置属性
- Android中的集中常用布局方式和按钮事件的处理方式
- android RelativeLayout(相对布局)详细说明
- 如何通过代码更改ANDROID的UI布局
- Android之布局属性
- Android开发之ConstraintLayout布局
- android布局学习利器-Hierarchy Viewer