布局文件main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/linear">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello"
android:id="@+id/tv" />
<LinearLayout android:orientation="horizontal"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:id="@+id/subLinear">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="@string/hello"
android:id="@+id/subTv" android:layout_weight="2"/>
<Button android:layout_width="match_parent"
android:layout_height="wrap_content" android:text="@string/hello"
android:id="@+id/btn" android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
使用布局的几种方式:
Resources res = getResources();
Context con = getApplicationContext();
1,直接通过resourceID引用xml文件中的布局
setContentView(R.layout.main);
2,使用LayoutInflater从布局文件中映射过来
LayoutInflater inflater = LayoutInflater.from(con);
View view = inflater.inflate(R.layout.main, null);
LinearLayout layout = (LinearLayout) view;
setContentView(layout);
上面第二行代码里的resourceID,只能是布局文件名对应的ID,不能是在资源文件中通过android:id设置的ID
3,用代码创建
//new out linear
LinearLayout outLinear = new LinearLayout(con);
outLinear.setOrientation(LinearLayout.VERTICAL);
//add tv to out linear
LinearLayout.LayoutParams tvParam = (android.widget.LinearLayout.LayoutParams) new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(con);
tv.setText(res.getString(R.string.hello));
outLinear.addView(tv, tvParam);
//new inner linear
LinearLayout innerLinear = new LinearLayout(con);
innerLinear.setOrientation(LinearLayout.HORIZONTAL);
//add tv to inner linear
LinearLayout.LayoutParams subTvParam = (android.widget.LinearLayout.LayoutParams) new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0.1f);
TextView subTv = new TextView(con);
subTv.setText(res.getString(R.string.hello));
innerLinear.addView(subTv, subTvParam);
//add btn to inner linear
LinearLayout.LayoutParams btnParam = (android.widget.LinearLayout.LayoutParams) new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0.9f);
Button btn = new Button(con);
btn.setText(res.getString(R.string.hello));
innerLinear.addView(btn, btnParam);
//add inner linear to out linear
LinearLayout.LayoutParams innerLinearParam = (android.widget.LinearLayout.LayoutParams) new LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
outLinear.addView(innerLinear, innerLinearParam);
setContentView(outLinear);
用代码创建时注意以下几个地方:
1,如果要设置线性布局中各个子view的weight属性,最好把各个子view的width(这里是横向的,如果是竖向的,应该就对应height了)设置成match_parent或fill_parent,如果是wrap_content,则最终的显示比例可能跟设置的weight不一样
2,weight越大,显示所占比例越小