Android——实现在纯Java代码里写布局
16lz
2021-01-23
效果图:
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RelativeLayout relativeLayout = new RelativeLayout(this); // 创建相对布局对象 relativeLayout.setBackgroundColor(Color.rgb(0,0,255)); // 整个布局设置为蓝色 Button button = new Button(this); // 创建按钮对象 RelativeLayout.LayoutParams btnParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, // wrap_content RelativeLayout.LayoutParams.WRAP_CONTENT); // wrap_content btnParams.addRule(RelativeLayout.CENTER_HORIZONTAL); // 居中水平对齐 button.setLayoutParams(btnParams); // 将设定好的样式作为setLayoutParams方法的参数,设置给这个按钮 button.setText("按钮"); // 设置按钮名字 relativeLayout.addView(button); // 将按钮添加到相对布局容器中 setContentView(relativeLayout); // 再设定布局形式为相对布局 }}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> </LinearLayout>
更多相关文章
- Android的帧布局
- android 设置linelayout让按钮自动适应屏大小
- Android布局优化:ViewStub标签实现延迟加载(源码解析原理)
- Android UI控件详解-Button(按钮)点击事件的5种写法
- 关于Android/java的复杂对象的深拷贝和浅拷贝
- android 拖拽图片&拖动浮动按钮到处跑
- Google Android之使用XML布局
- Android Studio App LinearLayout多层布局嵌套
- Android 中实现FlowLayout 布局