我正在编写一个自定义视图,从RelativeLayout扩展,我想以编程方式调整它,我该怎么办?
自定义视图类是这样的:
public ActiveSlideView(Context context, AttributeSet attr){
super(context, attr);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(inflater != null){
inflater.inflate(R.layout.active_slide, this);
}
Run Code Online (Sandbox Code Playgroud) 这是我的观点,我希望将layout_width更改为"10dip".我该如何以编程方式执行此操作?注意,这不是LinearLayout,而是View.
<View
android:id="@+id/nutrition_bar_filled"
android:background="@drawable/green_rectangle"
android:layout_height="30dp"
android:layout_width="50dp"/>
Run Code Online (Sandbox Code Playgroud)
我知道LayoutParams.如何使用它将宽度设置为10dip?
我创建了一个名为MyDraw的自定义视图,这是我的MyDraw代码,
public class MyDraw extends View {
public MyDraw(Context context) {
super(context);
}
public MyDraw(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyDraw(Context context, AttributeSet attrs) {
super(context, attrs);
}
........................................
}
Run Code Online (Sandbox Code Playgroud)
我使用包名称在XML文件中添加了视图.它工作正常.现在我想在运行时为MyDraw设置高度和宽度,因为我使用了以下代码,
mMyDraw.setLayoutParams(new LayoutParams(220, 300));
Run Code Online (Sandbox Code Playgroud)
但我得到了例外,
java.lang.ClassCastException:android.view.ViewGroup $ LayoutParams
如何解决这个异常?请帮我..