我有一小段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>
的View
类有一个充气方法,其包装LayoutInflater.inflate
。您应该可以使用:
LinearLayout ll = (LinearLayout) inflate(context, R.layout.amount_widget, this);
从xml扩展您的小部件。addView()
不需要调用,因为inflate会为您添加新膨胀的视图!
编辑:仅需注意,因为此视图已经是LinearLayout,所以不需要将要膨胀的xml的根也设为LinearLayout。如果仅对EditText进行充气,然后仅将其添加到父级中,而不是在父级中嵌套第二个LinearLayout,则可以提高性能。您可以直接AmountWidget
在xml中添加的任何地方设置LinearLayout属性(例如背景和填充)。在这种特定情况下,这无关紧要,但是如果您的情况有很多嵌套视图,可能会很高兴知道下一步。
Edit2:View
该类具有三个构造函数:View(Context),View(Context,AttributeSet)和View(Context,AttributeSet,int)。当系统从xml扩展视图时,它将使用后两个视图之一。任何自定义View都需要实现所有这三个构造函数。重用代码时,一个简单的方法是这样的:
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在每次膨胀时都以相同的方式创建,那么这将起作用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句