[英]How to inflate Android View in LinearLayout class?
我有一小段xml,我将在我的应用程序中的很多地方使用它。 出于这个原因,我想将它存储在一个单独的文件中。 所以我创建了mywidget.xml,其中包含了我的xml。 然后我尝试在mywidget.java中膨胀它,之后我想将它包含在不同的xml文件中,如下所示:
<com.mycom.android.ui.widget.AmountWidget android:layout_width="fill_parent" android:layout_height="wrap_content"></com.mycom.android.ui.widget.AmountWidget>
在我的java文件中,我尝试像这样膨胀初始的xml:
public class AmountWidget extends LinearLayout {
public AmountWidget(Context context) {
super(context);
LinearLayout ll = (LinearLayout) findViewById(R.layout.amount_widget);
addView(ll);
}
}
但是使用上面的代码我得到一个错误,说com.mycom.android.ui.widget.AmountWiget类有一个错误。
我的问题:有没有人知道如何给布局充气,以便我可以将它作为另一个xml布局文件中的类使用?
小部件中的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="wrap_content"
android:layout_margin="10dp"
android:padding="10dp"
android:background="@layout/border"
>
<EditText
android:id="@+id/payment_amount_major"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="35sp"
android:textStyle="bold"
android:inputType="number"
android:digits="0,1,2,3,4,5,6,7,8,9"
android:maxLength="9"
android:gravity="right"
/>
</LinearLayout>
试试这个:
mContainerView = (LinearLayout)findViewById(R.id.parentView);
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.row, null);
mContainerView.addView(myView);
mContainerView
是LinearLayout,它包含你的EditText
, row
是你的xml文件名。
最简单的解决方案
LinearLayout item = (LinearLayout )findViewById(R.id.item);//where you want to add/inflate a view as a child
View child = getLayoutInflater().inflate(R.layout.child, null);//child.xml
item.addView(child);
ImageView Imgitem = (ImageView ) child.findViewById(R.id.item_img);
Imgitem.setOnClick(new ...
View
类有一个包装LayoutInflater.inflate
方法 。 你应该可以使用:
LinearLayout ll = (LinearLayout) inflate(context, R.layout.amount_widget, this);
从xml中扩展您的小部件。 addView()
调用addView()
,因为addView()
将为您添加新增加的视图!
编辑:只是一个注释,因为这个View已经是一个LinearLayout,所以你不需要让你膨胀的xml的根也是一个LinearLayout。 如果只对EditText进行充气并将其添加到父级,而不是在父级中嵌套第二个LinearLayout,则可以提高性能。 您可以直接在AmountWidget
上设置LinearLayout属性(例如背景和填充),无论它在xml中添加。 在这种特定情况下,这应该不会太重要,但如果你有许多嵌套视图的情况,可能会很高兴知道。
Edit2: View
类有三个构造函数 :View(Context),View(Context,AttributeSet)和View(Context,AttributeSet,int)。 当系统从xml中膨胀视图时,它将使用后两者中的一个。 任何自定义视图都需要实现所有这三个构造函数。 在重用代码时执行此操作的简单方法如下:
public AmountWidget(Context context) {
super(context);
LinearLayout ll = (LinearLayout) inflate(context, R.layout.amount_widget, this);
}
public AmountWidget(Context context, AttributeSet attrs) {
this(context);
}
public AmountWidget(Context context, AttributeSet attrs, int defStyle) {
this(context);
}
如果您不关心属性或样式参数是什么,并且只是希望AmountWidget在其膨胀时创建的相同,这将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.