Android:如何设置视图的高度?

时间:2012-11-20 11:30:56

标签: android android-layout

我创建了一个按钮并使用addView()onClickListener()中绘制一些图表。但是如果图表超出界限,它将不会自动扩展视图的高度。所以我想在绘制所有图表时添加视图的高度。我尝试使用getLayoutParams().height来修改高度,但它不起作用。

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>

我也尝试在for循环之外调用onMeasure(getWidth(),addHeight),但它仍无效。

 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(widthMeasureSpec, widthMeasureSpec);
 }

1 个答案:

答案 0 :(得分:0)

如果您想以八种方式执行,Chart课程应该实施onMeasure()。如果它只是一个黑客,你可以使用AbsoluteLayout。你也可以设置布局参数,但是你应该拨打updateViewLayout()甚至requestLayout()