【问题标题】:Trying to create a custom layout that extends constraintlayout尝试创建扩展约束布局的自定义布局
【发布时间】:2020-06-14 23:04:48
【问题描述】:

所以我有这个自定义布局。

public class MyCustomView extends ConstraintLayout {
    private Button myFancyButton;
    public MyCustomView (@NonNull Context context, AttributeSet attrs) {
        super(context,attrs);
    myFancyButton = findViewById(R.id.button); //THIS IS NULL
    }
    public void init(){
    myFancyButton = findViewById(R.id.button); //WORKS GREAT
    }
}

问题是我宁愿不创建一个函数“init”来完成适合构造函数的工作。我面临的问题是在构造函数中调用 findViewById 导致它为空。在 MyCustomView 对象上使用 init 函数就可以了。但我更愿意在构造函数中这样做。

对应的 XML 文件如下所示。

<?xml version="1.0" encoding="utf-8"?>
<se.test.test.test.MyCustomView xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

        <Button
            android:id="@+id/button"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:text="B1"
            android:textSize="30sp"/>

</se.test.test.test.MyCustomView>

【问题讨论】:

    标签: java android layout view


    【解决方案1】:

    您需要将该代码放入onFinishInflate() - 当布局及其子级膨胀时调用该方法。

    @Override
    public void onFinishInflate() {
        myFancyButton = findViewById(R.id.button)
    }
    

    https://developer.android.com/reference/android/view/View#onFinishInflate()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 2011-07-30
      • 2018-01-23
      • 2012-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多