1
我已經創建了一個按鈕,並使用addView()
在onClickListener()
中繪製了一些圖表。但是,如果圖表出界,它不會自動擴展視圖的高度。所以我想在繪製所有圖表時添加視圖的高度。我嘗試使用getLayoutParams().height
來修改高度,但它不起作用。Android:如何設置視圖的高度?
public class MainActivity extends Activity {
private TableLayout layout;
private Button btnDraw;
public void onCreate(Bundle savedInstanceState){
layout=findViewById((TableLayout) findViewById(R.id.tableLayout));
btnDraw=findViewById((Button) findViewById(R.id.btnDraw));
btnDraw.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
layout.addView(new Chart(MainActivity.this)
}
});
}
class Chart extends View {
public void onDraw(Canvas c) {
int addHeight=0;
for(...){ //draw several chart
...
addHeight+=500;
}
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) layout.getLayoutParams();
params.height += addHeight;
layout.setLayoutParams(params);
}
}
}
這裏是XML代碼
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<TableLayout
android:id="@+id/tableLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<Button
android:id="@+id/btnDraw"
android:layout_span="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw" />
</TableRow>
...
</TableLayout>
</ScrollView>
我也嘗試調用外部onMeasure(getWidth(),addHeight)
for循環,但它仍然無法正常工作。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(widthMeasureSpec, widthMeasureSpec);
}