Android 以编程方式设置LayoutParams

Android 以编程方式设置LayoutParams,android,Android,我想在计算完所有视图的参数后设置LinearLayout的参数 我正在尝试设置与父视图高度相关的LinearLayout高度。父视图的高度是根据它的布局权重计算出来的,所以我通过getmeasuredeheight()得到高度 我的代码: @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); RelativeLayout lay = (Re

我想在计算完所有视图的参数后设置LinearLayout的参数

我正在尝试设置与父视图高度相关的LinearLayout高度。父视图的高度是根据它的
布局权重计算出来的,所以我通过
getmeasuredeheight()得到高度

我的代码:

@Override
public void onWindowFocusChanged(boolean hasFocus) {

  super.onWindowFocusChanged(hasFocus);
  RelativeLayout lay = (RelativeLayout) findViewById(R.id.alt);
  LinearLayout bar = (LinearLayout) findViewById(R.id.barLay);

  int layH = lay.getMeasuredHeight();
  int barH = layH / 4;
  LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
  params.height = barH;
  bar.setLayoutParams(params);
} 
Eclipse调试器在此行停止程序

LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
我找不到有什么问题?设置参数时是否出错?

尝试更改此设置

LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
对此

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bar.getLayoutParams();

@LocHa问我布局的类型后,我尝试将父布局的类型更改为LinearLayout,这是RelativeLayout,最后它对我起了作用。

LayoutParams的类型实际上是由视图的父级设置的,因此bar.getLayoutParams()应该返回类型为
RelativeLayout.LayoutParams
的对象。通过显式转换为
LinearLayout.LayoutParams
,我希望您的日志猫包含如下行:

Caused by: java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
将其更改为此应该可以实现以下目的:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) bar.getLayoutParams();
或者,因为高度在基类中,所以根本不要使用它:

ViewGroup.LayoutParams params = bar.getLayoutParams();

张贴日志?这将有助于Logcat有6000行我不知道该发布什么部分:(控制栏在什么布局类型内?我要设置参数的布局是线性的,其父级是相对的。我将尝试将relativeLayout更改为LinearLayout,并将结果写在此处,效果很好!谢谢@Lochat这就是为什么您需要知道其父级布局类型的原因。因为其父级是relativeLayout。因此您必须强制转换布局。)utParams到RelativeLayout.LayoutParams。