我正在尝试创建没有 xml 的自定义视图
public class MyView extends ViewGroup {
public MyView (Context context) {
super(context);
setBackgroundColor(0xffff0000);
RelativeLayout base = new RelativeLayout(context);
RelativeLayout.LayoutParams rP = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
base.setBackgroundColor(0xff00ff00);
base.setLayoutParams(rP);
RelativeLayout.LayoutParams iP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ImageView icon = new ImageView(context);
icon.setBackgroundResource(android.R.drawable.ic_menu_add);
icon.setLayoutParams(iP);
addView(icon);
addView(base);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
并在活动中使用它
MyView myview = new MyView(this);
WindowManager.LayoutParams baseParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
addContentView(myview, baseParams);
但是 LayoutParams 不起作用,它什么也不显示
我必须使用这个 onLayout 让它显示,并且基本布局不是 MATCH_PARENT 并且图标不是 WRAP_CONTENT
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final View child = getChildAt(0);
final View child2 = getChildAt(1);
child.layout(0, 0, 300, 300);
child2.layout(0, 0, 300, 300);
}
我也尝试在布局中添加图标,但应用程序会崩溃
base.addView(icon);
是否可以在不硬编码大小和位置的情况下创建此布局?
我检查了RelativeLayout.LayoutParams,但找不到任何方法将其centerInParent 设置为true。
http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_menu_add"
android:layout_centerInParent="true"
/>
</RelativeLayout>