我想在计算所有视图参数后设置我的LinearLayout参数。
我正在尝试设置与父视图高度相关的LinearLayout高度。父视图的高度根据其layout_weight
计算,因此我得到getMeasuredHeight();
的高度
我的代码:
@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 Debugger在此行停止程序;
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
我找不到可能出现的问题?设置参数是否我做错了什么?
答案 0 :(得分:0)
尝试更改此
LinearLayout.LayoutParams params = (LayoutParams) bar.getLayoutParams();
到这个
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) bar.getLayoutParams();
答案 1 :(得分:0)
在@LocHa问我布局的类型后,我尝试将父布局的类型更改为LinearLayout,即RelativeLayout,最后它对我有效。
答案 2 :(得分:0)
LayoutParams的类型实际上是由视图的父级设置的,因此bar.getLayoutParams()应该返回类型为RelativeLayout.LayoutParams
的对象。通过显式转换为LinearLayout.LayoutParams
,我希望您的logcat包含这样一行:
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();