java - 如何在 LinearLayout 类中膨胀 Android View?

标签 java android xml android-layout

我有一小段 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 是包含您的 EditTextrow 是您的 xml 文件名的 LinearLayout。

关于java - 如何在 LinearLayout 类中膨胀 Android View?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19118943/

相关文章:

Java 一个包含其他 sibling 的子类

java - Spring Boot 测试加载 ApplicationContext 失败

android - 如何读写Android NFC标签?

c# - 使用 OpenXML 时以正确的顺序插入子元素

java - 将 Context.xml 放在 WAR 文件中的什么位置?

sql - 生成 XML 文件时收到 PL/SQL 错误

java - 在正则表达式中设置最小和最大字符

java - 获取节点子节点时 Android Firebase 实时数据库错误

android - 如何在 Android Studio 中包含 *.so 库?

java - React Native Amplify AWS 包与 firebase 冲突