代码之家  ›  专栏  ›  技术社区  ›  Karlo A. López

无法调用自定义ConstraintLayout类的方法?

  •  0
  • Karlo A. López  · 技术社区  · 7 年前

    我想做一个定制的ConstraintLayout,这样我就可以从初始化它的活动中触发一些函数。

    我有以下代码:

    首先在布局中初始化自定义视图:

    <package.com.app.Main.LavadasView
            android:id="@+id/main_autolavados_lavadas_lavadas_view"
            android:layout_width="0dp"
            android:layout_height="25dp"
    ...
            />
    

    Java类

    public class LavadasView extends ConstraintLayout {
    
    
        public LavadasView(Context context,AttributeSet attrs) {
            super(context);
    //Inflate view from XML layout file
            LayoutInflater inflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(R.layout.lavadas_view, this);
    
    
    
        }
    
        public void resetView(){
            //Some ui updates
        }
    
    }
    

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

    在我的活动中,我得到了 findViewById

    LavadasView lavadasView = (LavadasView) findViewById(R.id.main_autolavados_lavadas_lavadas_view);
    
    //Call this method later on
            lavadasView.resetView();
    

    那我做错什么了?我查了一下,这是获得布局实例的正确方法吗?

    谢谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Pawel Laskowski    7 年前

    问题出在你的 LavadasView . 当你的 Activity 它会称之为 LavadasView(Context context, AttributeSet attrs) super(context, attrs) 对于 ConstraintLayout super(context) NullPointerException .