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的总布局方式。
运行效果如下: