作者:津pig | 来源:互联网 | 2024-11-22 11:20
Android中我们知道,可以用main.xml等方式来布局一个activity的状态,但是我们也可以用代码的方式来进行布局,从而抛弃那种xml方式的布局,代码如下:
- package com.andy.android.layout;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.ViewGroup;
- import android.widget.Button;
- import android.widget.LinearLayout;
- import android.widget.TextView;
-
- public class LayoutTestActivity extends Activity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- LinearLayout layout = new LinearLayout(getApplicationContext());
- LinearLayout.LayoutParams layoutParm = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
- layout.setOrientation(LinearLayout.VERTICAL);
-
-
- TextView text = new TextView(getApplicationContext());
-
- LinearLayout textLayout = new LinearLayout(getApplicationContext());
- LinearLayout.LayoutParams textParm = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
- textLayout.setOrientation(LinearLayout.HORIZONTAL);
- text.setText("just for test");
- text.setTextSize(20);
-
- layout.addView(text, textParm);
-
- Button btn = new Button(getApplicationContext());
- LinearLayout btnLayout = new LinearLayout(getApplicationContext());
- LinearLayout.LayoutParams btnParm = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
- btnLayout.setOrientation(LinearLayout.HORIZONTAL);
- btn.setText("just for button");
- btn.setTextSize(20);
- layout.addView(btn, btnParm);
-
- super.setContentView(layout,layoutParm);
- }
这里显示了一个文本和一个button,通篇都是用代码进行布局的,主要流程如下:
先new一个线性布局,设置其布局的属性。然后new一个文本,设置好其参数,然后add到layout中去。
button也是如此,
最终将线性布局器设置为activity的总布局方式。
运行效果如下: