2012-11-20 78 views
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); 
} 

回答

0

,如果你想这样做的八路你Chart类应该实现onMeasure()。如果它只是一个黑客,你可以使用AbsoluteLayout。你也可以玩设置参数,但你应该打电话updateViewLayout()甚至可能requestLayout()

相关问题