在android UI开发过程中,有些需要显示的内容并不是在布局的时候可以预知的,这就需要使用动态布局。本例仅采用TableLayout来说明如何动态布局(其余Layout也可以)
1.在Layout文件中定义预先知道的部分,(一个TableLayout,一个进度条, 两个按键)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:stretchColumns="*">
<TableRow
android:id="@+id/tablerow_info"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TableRow>
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0" />
</TableLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btStart"
android:onClick="onButtonStartClicked"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btStop"
android:onClick="onButtonStopClicked"/>
</LinearLayout>
</LinearLayout>
2.在代码中增加需要动态添加的部分
public void updateWayInfo()
{
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels / ( mIsForward ? mForward.length : mBackward.length);
String[] way = mIsForward ? mForward : mBackward;
TableRow row = (TableRow)this.findViewById(R.id.tablerow_info);
for( String station : way)
{
TextView text = new TextView(this);
text.setMaxWidth(width/2);
text.setGravity(Gravity.CENTER);
text.setText(station);
row.addView(text);
}
}
注意,本函数的调用需要在
setContentView(R.layout.activity_ttsexample);
调用过后,否则layout各对象都还没有创建,会直接导致崩溃
3. 站点名信息
<string-array name="forward">
<item>三门路新江湾城</item>
<item>市光路政立路</item>
<item>淞沪路政立路</item>
<item>五角场淞沪路</item>
<item>邯郸路国定路</item>
<item>国定路邯郸路</item>
<item>政民路国定路</item>
<item>肺科医院</item>
<item>武东路政民路</item>
<item>武东路武川路</item>
<item>武川路政立路</item>
<item>国权北路政立路</item>
<item>三门路吉浦路</item>
<item>吉浦路青石路</item>
<item>青石路国权北路</item>
<item>殷高路吉浦路</item>
<item>高境庙</item>
<item>高境新村</item>
<item>殷高西路桥</item>
<item>新二路淞南十村</item>
<item>新二路通南路</item>
<item>通南路新二路</item>
</string-array>
4.模拟器上运行的效果图