数据绑定:缺少id为的必需视图

mrzz3bfm  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(485)

我创建了一个应用程序使用绑定,我得到了一个错误,我无法解决。错误是

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newtest/com.example.mylibrary.MainActivity1}: java.lang.NullPointerException: Missing required view with ID: com.example.newtest:id/myRecyclerview

谢谢!

public class MainActivity1 extends AppCompatActivity {

    RecyclerView.LayoutManager layoutManager;
    ArrayList<POJOimage>pojoImageArrayList;
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        layoutManager = new LinearLayoutManager(this);
        binding.myRecyclerview.setLayoutManager(layoutManager);
        init();
    }

xml格式:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity1"
    android:background="#000"
    android:padding="10dp">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myRecyclerview"/>
</androidx.constraintlayout.widget.ConstraintLayout>
nkkqxpd9

nkkqxpd91#

为了正确使用数据绑定,xml的最外层标记应该是layout(其中包含您可能希望传递给xml的数据)。对于您的情况,您没有数据,但最外层的标记仍然应该是布局,以便识别绑定。

<?xml version="1.0" encoding="utf-8"?>
<layout>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity1"
    android:background="#000"
    android:padding="10dp">

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myRecyclerview"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

你的主要活动代码,

public class MainActivity extends AppCompatActivity {

    RecyclerView.LayoutManager layoutManager;
    ArrayList<POJOimage>pojoImageArrayList;
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        layoutManager = new LinearLayoutManager(this);
        binding.myRecyclerview.setLayoutManager(layoutManager);
        init();
    }
}

相关问题