Android FrameLayout的内容未显示
由于常规Android FrameLayout的内容未显示,android,android-layout,Android,Android Layout,由于常规按钮类的边距和填充问题,我一直在开发扩展框架布局的自定义布局。 我遇到了一个问题,布局的内容无法显示。 一旦我将此内容更改为另一个内容,例如RelativeLayout内容就会显示出来 这是我的相关代码: private static final int COLOR = R.styleable.MyButton_color; private static final int TEXT = R.styleable.MyButton_text; public MyButton(Contex
按钮
类的边距和填充问题,我一直在开发扩展框架布局
的自定义布局
。
我遇到了一个问题,布局的内容无法显示。
一旦我将此内容更改为另一个内容,例如RelativeLayout
内容就会显示出来
这是我的相关代码:
private static final int COLOR = R.styleable.MyButton_color;
private static final int TEXT = R.styleable.MyButton_text;
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutParams backgroundParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
backgroundParams.gravity = Gravity.FILL;
background = new ImageView(context, null, defStyle);
addView(background, backgroundParams);
text = new TextView(context, null, defStyle);
text.setTypeface(null, Typeface.BOLD);
LayoutParams textParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textParams.gravity = Gravity.CENTER;
addView(text, textParams);
TypedArray a = context.obtainStyledAttributes(R.styleable.MyButton);
try {
setColor(Color.values()[a.getInteger(COLOR, 0)]);
setText(a.getString(TEXT));
} finally {
a.recycle();
}
}
public void setText(CharSequence text) {
this.text.setText(text);
}
private void setColor(Color color) {
switch (color) {
case ORANGE:
text.setTextColor(getContext().getResources().getColor(R.color.text_blue));
background.setImageResource(R.drawable.button_orange);
break;
case BLUE:
//TODO set colors
break;
}
}
这是一个特殊的布局,它在大多数API版本中设置了一个不调用绘图函数的标志 要克服此问题,请在构造时将标志设置为false:
public MyButton(
...
setWillNotDraw(false);
...
答案很明显
LayoutParams backgroundParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
必须由
LayoutParams backgroundParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
当然,这同样适用于
textParams
。您可能希望添加具有特定LayoutParams
的视图,更准确地说是FrameLayout.LayoutParams
我使用的是FrameLayout.LayoutParams
。它们在我的导入中,我在上面的代码示例中没有提供。