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 {
- /** Called when the activity is first created. */
- @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);
-
- //文本text
- 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);
- //將文本add到線性布局器中
- layout.addView(text, textParm);
- //button
- 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);
- //設置activity布局采用layout線性布局,布局方式采用layoutParm方式。
- super.setContentView(layout,layoutParm);
- }
這裡顯示了一個文本和一個button,通篇都是用代碼進行布局的,主要流程如下:
先new一個線性布局,設置其布局的屬性。然後new一個文本,設置好其參數,然後add到layout中去。
button也是如此,
最終將線性布局器設置為activity的總布局方式。
運行效果如下: