【问题标题】:Android: How to initialise a custom View in code and connect it to an existing xml viewAndroid:如何在代码中初始化自定义视图并将其连接到现有的 xml 视图
【发布时间】:2019-12-02 16:21:20
【问题描述】:

我有自己的自定义视图类,如下所示:

public class speak extends ConstraintLayout implements View.OnClickListener {

    
    private TextView text;
    private ImageView img;

    public speak(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.speak,
                0, 0);
        try {
            
            text = findViewById(a.getResourceId(R.styleable.speak_text,0));
            img = findViewById(a.getResourceId(R.styleable.speak_img, 0));

        } finally {
            a.recycle();
        }

    }
}

有了这个我创建了attr.xml,我把这个资源放在这里:

<declare-styleable name="speak">      
    <attr name="text" format="string"/>
    <attr name="img" format="reference"/>
</declare-styleable>

我还创建了我自己的自定义视图外观的布局 xml。这样我就可以在activity_main.xml 中轻松添加多个视图。我首先在activity_main.xml 中添加一个视图。但现在我想将它链接到onCreate 中的自定义视图类。我正在做的是这样的:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    speak sl =  findViewById(R.id.ss);
    sl.seImage(getResources().getIdentifier("com.example.app:drawable/img.png", null, null));
}

setImage 是我自己的 customView 中组件的设置器。但是,这将返回一个 null pointer exception,我想我理解它,因为我没有创建一个新的 speak 对象并在构造函数中传递属性等等。

创建一个新的视图对象,但同时传递给它一个 xml 元素,该元素将其在屏幕上的位置与其他东西分开。

我也不确定应该在构造函数中将什么传递给AttributeSet。

更新

这是错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)

这是因为我的 setter 包含 img.SetImageResource(int) 以获取可绘制 Id 并将 te 图像设置为可绘制文件夹中的该图像

【问题讨论】:

    标签: android android-layout android-custom-view android-resources


    【解决方案1】:

    请查看我使用过的 GoEditText:

     public class GoEditText extends FrameLayout {
         private TextInputLayout inputLayout;
         private AppCompatEditText editText;
    
         public GoEditText(Context context) {
            super(context);
            init(context, null);
          }
    
           public GoEditText(Context context, AttributeSet attrs) {
              super(context, attrs);
              init(context, attrs);
           }
    
            private void init(Context context, AttributeSet attrs) {
               this.context = context;
               LayoutInflater.from(context).inflate(R.layout.go_edit_text, this, true);
               inputLayout = findViewById(R.id.inputLayout);
               editText = findViewById(R.id.editText);
               if (attrs != null) {
                 TypedArray typedArray = context.obtainStyledAttributes(attrs, 
                    R.styleable.GoEditText, -1, 0);
                 int edtType = typedArray.getInt(R.styleable.GoEditText_edtTextType, 0);
                 boolean isEditable = typedArray.getBoolean( 
                   R.styleable.GoEditText_isEditAble, true);
               }
    
    }
    

    下面是xml go_edit_text.xml

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/inputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:passwordToggleDrawable="@null">
    
        <android.support.v7.widget.AppCompatEditText
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            style="@style/CJEditText"
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawablePadding="5dp"
            app:backgroundTint="@color/gray_3" />
    
    </android.support.design.widget.TextInputLayout>
    

    现在可以直接在 acitivity.xml 中使用了

    <com.package.name.component.GoEditText
            android:id="@+id/myid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:edtTextType="selection"
            app:errorMsg="@string/error_employee_type"
            app:hint="@string/hint_employee_type" />
    

    现在在 onCreate

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_home);
         GoEditText edt= findViewById(R.id.myId);
         edt.editText.setText("hello");
    }
    

    或者您可以在 CustomView 中创建一个 getter 方法来表示 edittext(在您的情况下为 imageView)

    【讨论】:

    • 那么通过有一个没有 AttributeSet 的构造函数可以在创建时调用它吗?
    • 这仍然没有解释如何在创建时调用它。您发布的内容与我已有的内容几乎一模一样。
    • 您可以在 xml 中使用您定义的自定义视图。你可以在问题中添加 activity_main.xml 吗?
    • 谢谢。我会检查并审查它。你对 使用 attr.xml
    • @SanjayKumar 这仍然给我一个空指针异常,因为您没有在 onCreate() 中调用构造函数来初始化元素
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多