1.代码
import android.annotation.SuppressLint; import android.app.Activity; import android.app.ActionBar.LayoutParams; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; //完全通过代码,来实现界面 public class LayoutOne extends Activity { private LinearLayout nameContainer = null; private LinearLayout addressContainer = null; private LinearLayout parentContainer = null; // 重写方法 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createNameContainer(); createAddressContainer(); createParentContainer(); setContentView(parentContainer); } // 创建nameContainer @SuppressLint("NewApi") private void createNameContainer() { nameContainer = new LinearLayout(this); // layout带有布局功能,例如设置横排、竖排,可以包含View,也可以包括替他layout,所以它同时也是一个容器 // 在Android学习中,我们使用fill_parent,包括xml中使用fill_parent,在API Level 8(Android // 2.2)后,改为match_parent LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); nameContainer.setLayoutParams(layoutParams); nameContainer.setOrientation(LinearLayout.HORIZONTAL); // 设置内部View TextView txtView = new TextView(this); txtView.setText("姓名:"); TextView valueView = new TextView(this); valueView.setText("张三"); nameContainer.addView(txtView); nameContainer.addView(valueView); } // 创建addressContainer @SuppressLint("NewApi") private void createAddressContainer() { addressContainer = new LinearLayout(this); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); addressContainer.setLayoutParams(layoutParams); addressContainer.setOrientation(LinearLayout.VERTICAL); TextView nameTextView = new TextView(this); nameTextView.setText("详细地址:"); TextView valueTextView = new TextView(this); valueTextView.setText("化纤长路---丁家庄"); addressContainer.addView(nameTextView); addressContainer.addView(valueTextView); } // 创建rootView,和前面两个container相似,不同的事addView不是加入普通的view,而是加入layout @SuppressLint("NewApi") private void createParentContainer() { parentContainer = new LinearLayout(this); LayoutParams lParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); parentContainer.setLayoutParams(lParams); parentContainer.setOrientation(LinearLayout.VERTICAL); parentContainer.addView(nameContainer); parentContainer.addView(addressContainer); } }
2.结果: