歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 中的布局方式之線性布局

Android 中的布局方式之線性布局

日期:2017/3/1 10:48:44   编辑:Linux編程

Android中我們知道,可以用main.xml等方式來布局一個activity的狀態,但是我們也可以用代碼的方式來進行布局,從而拋棄那種xml方式的布局,代碼如下:

  1. package com.andy.android.layout;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.ViewGroup;
  5. import android.widget.Button;
  6. import android.widget.LinearLayout;
  7. import android.widget.TextView;
  8. public class LayoutTestActivity extends Activity {
  9. /** Called when the activity is first created. */
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. LinearLayout layout = new LinearLayout(getApplicationContext());
  14. LinearLayout.LayoutParams layoutParm = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
  15. layout.setOrientation(LinearLayout.VERTICAL);
  16. //文本text
  17. TextView text = new TextView(getApplicationContext());
  1. //設置文本屬性
  2. LinearLayout textLayout = new LinearLayout(getApplicationContext());
  3. LinearLayout.LayoutParams textParm = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
  4. textLayout.setOrientation(LinearLayout.HORIZONTAL);
  5. text.setText("just for test");
  6. text.setTextSize(20);
  1. //將文本add到線性布局器中
  2. layout.addView(text, textParm);
  3. //button
  4. Button btn = new Button(getApplicationContext());
  5. LinearLayout btnLayout = new LinearLayout(getApplicationContext());
  6. LinearLayout.LayoutParams btnParm = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
  7. btnLayout.setOrientation(LinearLayout.HORIZONTAL);
  8. btn.setText("just for button");
  9. btn.setTextSize(20);
  10. layout.addView(btn, btnParm);
  11. //設置activity布局采用layout線性布局,布局方式采用layoutParm方式。
  12. super.setContentView(layout,layoutParm);
  13. }
這裡顯示了一個文本和一個button,通篇都是用代碼進行布局的,主要流程如下:

先new一個線性布局,設置其布局的屬性。然後new一個文本,設置好其參數,然後add到layout中去。

button也是如此,

最終將線性布局器設置為activity的總布局方式。


運行效果如下:

Copyright © Linux教程網 All Rights Reserved