android 自定义relativelayout,android-自定义RelativeLayout上的setBackground无法正常工作

所有,

我有一个自定义的RelativeLayout,在加载视图之后,我想将RelativeLayout的背景更改为可绘制的.我不知道为什么它不起作用…似乎应该很简单.

这是我的自定义布局代码:

public class InputBoxView extends RelativeLayout {

//My variables

//Irrelevants initalizers

//Method in question

public void addErrorBox() {

setBackgroundResource(R.drawable.error_border);

}

}

这是自定义视图的布局文件:

android:layout_width="match_parent"

android:layout_height="@dimen/standard_line_height"

android:background="@android:color/white" >

style="@style/space_view"

android:layout_alignParentTop="true" />

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerVertical="true">

android:id="@+id/input_box_textview"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight=".35"

android:padding="10dp"

android:text="Key" />

android:id="@+id/input_box_edittext"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="0.65"

android:layout_marginRight="10dp" />

style="@style/space_view"

android:layout_alignParentBottom="true" />

这是我的error_border

当我从活动中调用addErrorBox方法时,背景没有明显变化,但是如果我在InputBoxView实例上放置一个断点,则在调用addErrorBox之后mBackground属性会发生变化,因此我相信背景会发生变化,但是没有更新.

我尝试在InputBoxView实例上调用invalidate(),但仍然无法正常工作.

有人有主意吗?

解决方法:

根据我对您提供的代码进行的测试,问题是

android:background="@android:color/white"

自定义视图xml的相对布局上.似乎忽略了您为InputBoxView使用setBackgroundResource设置的任何内容.

删除该属性后,便可以看到红色边框背景.

一种解决方案是从xml中删除RelativeLayout,因为InputBoxView已经从它扩展了,并设置了白色背景,宽度高度以及在您为自定义视图充气时不设置的内容.

因此,您的xml可能如下所示

并在您的InputBoxView中

public InputBoxView(Context context, AttributeSet attrs) {

super(context, attrs);

LayoutInflater inflater = (LayoutInflater) context

.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

inflater.inflate(R.layout.some_custom, this, true);

// Set what you need for the relative layout.

setBackgroundColor(Color.WHITE);

}

public void addErrorBox() {

setBackgroundResource(R.drawable.error_border);

invalidate();

}

或者,您可以将ID添加到RelativeLayout并直接修改背景,而不是在InputBoxView上.

对于invalidate,您需要在onCreate之后使用它,以便重新绘制它.

希望能帮助您解决问题或至少为您指明正确的方向.

标签:android-layout,android

来源: https://codeday.me/bug/20191121/2055154.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值