[英]Custom view does not inflate from XML when referenced in Fragment.xml Android Application Development
[英]Why does mLayoutParams is null when i inflate from xml?
这是用于膨胀视图的代码:
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.test, null);
我的test.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="50px">
<Button android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
我在此行下面设置了断点,这mLayoutParams
test.xml
膨胀,并发现视图中的mLayoutParams
实例为空。 我想如果在第二个膨胀参数中指定父视图,则不会发生这种情况。
但它仍然感觉很奇怪:如果mLayoutParams
为null,那么我为什么要在LinearLayout元素中设置layout_width
和layout_height
属性。
使用此代码
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
要么
LayoutInflater inflater =(LayoutInflater)getLayoutInflater();
在此之后,我认为你的问题将得到解决。
使用以下方式创建。
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.