我有一段时间没有在网上找到答案,现在我问你能不能帮我。
简短:我应该如何覆盖addView() (或其他东西)以将XML中定义的视图添加到我的“自定义视图膨胀的XML布局”中
Long:我想为我的android应用程序创建一个自定义视图,所以我从RelativeLayout创建了一个干净的子类。在这种情况下,我让充气器加载一个xml布局,以获得一个良好的样式。
但是现在,我想在自定义视图中添加一些内容,但不想以渐进的方式添加它(这只是简单的工作),而是使用xml。我无法跨越头脑中的空白去寻找解决办法.
代码:自定义类:
public class Slider extends RelativeLayout {
private RelativeLayout _innerLayout;
public Slider(Context context) {
super(context);
init();
}
public Slider(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
protected void init() {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_innerLayout = (RelativeLayout) layoutInflater.inflate(R.layout.layout_r, this);
}
@Override
public void addView(View child) {
//if (_innerLayout != null) _innerLayout.addView(child);
super.addView(child);
}
... all other addView's are overridden in the same way使用子类的XML文件:
<packagename....Slider
android:id="@+id/slider1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/Red" >
<TextView
android:id="@+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HEADING" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="bbb" />
...TextView和Button被添加到子类..。当然..。但在那之后,我得到了3个孩子在滑雪板,TextView,按钮和我的充气布局从R.layout.layout_r,但我只是想要一个孩子( layout_r)与按钮和TextView在其中。
正如您在addView中所看到的,我尝试将传递的“视图子”添加到_innerLayout中。那不起作用。Android框架不断调用addView,并以StackOverFlowError结束。
还有两件事要告诉你:
是原因吗?
你能帮我吗?
发布于 2014-02-22 09:05:46
您可以查看如何将子视图充气到自定义视图这里(vogella教程)中。
你需要的是:
<merge>标记定义带有子元素的布局发布于 2017-08-25 11:11:30
只需在自定义视图( addView() )中重写Slider方法,并检查childs的计数。如果是getChildCount() == 0,那么这是第一个加法,它是视图初始化。
Kotlin的例子:
override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
if (childCount == 0) {
super.addView(child, index, params)
} else {
// Do my own addition
}
}https://stackoverflow.com/questions/16085821
复制相似问题