RecyclerView 对象上的 setLayoutManager() 导致 onCreate() 崩溃

问题描述 投票:0回答:0

一切正常,直到我运行 recyclerViewMeals.setLayoutManager(layoutManager)。在调试模式下,该方法不会导致崩溃,但一旦我跨过 onCreate() 的右括号“}”,程序就会崩溃。注释掉 recyclerViewMeals.setLayoutManager(layoutManager) 行可防止程序崩溃,但 recyclerViewMeals 不显示任何内容。

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.example.myapplication.Adapter.MealsAdapter;
import com.example.myapplication.Model.Meal;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerViewMeals;
    private MealsAdapter mealsAdapter;
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        List<Meal> mealList = new ArrayList<>();
        mealList.add(new Meal(1, 1, "Chicken Breast", 340, 34, Calendar.getInstance()));
        mealList.add(new Meal(2, 1, "Rice", 230, 4, Calendar.getInstance()));
        recyclerViewMeals = (RecyclerView) findViewById(R.id.recyclerViewMeals);
        recyclerViewMeals.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerViewMeals.setLayoutManager(layoutManager);
        mealsAdapter = new MealsAdapter(this, mealList);
        recyclerViewMeals.setAdapter(mealsAdapter);
    }
}
package com.example.myapplication.Model;

import java.util.Calendar;

public class Meal {
    private int id;
    private int userId;
    private String name;
    private int calories;
    private int protein;
    private Calendar date;

    public Meal() {}

    public Meal(int id, int userId, String name, int calories, int protein, Calendar date) {
        this.id = id;
        this.userId = userId;
        this.name = name;
        this.calories = calories;
        this.protein = protein;
        this.date = date;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getCalories() {
        return calories;
    }

    public void setCalories(int calories) {
        this.calories = calories;
    }

    public int getProtein() {
        return protein;
    }

    public void setProtein(int protein) {
        this.protein = protein;
    }

    public Calendar getDate() {
        return date;
    }

    public void setDate(Calendar date) {
        this.date = date;
    }
}

package com.example.myapplication.Adapter;

import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.R;

public class MealsViewHolder extends RecyclerView.ViewHolder{
    TextView textViewMealName, textViewMealCalories, textViewMealProtein;

    public MealsViewHolder(@NonNull View itemView) {
        super(itemView);
        textViewMealName = (TextView) itemView.findViewById(R.id.textViewMealName);
        textViewMealCalories = (TextView) itemView.findViewById(R.id.textViewMealCalories);
        textViewMealProtein = (TextView) itemView.findViewById(R.id.textViewMealProtein);
    }
}

package com.example.myapplication.Adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication.Model.Meal;
import com.example.myapplication.R;

import java.util.List;


public class MealsAdapter extends RecyclerView.Adapter<MealsViewHolder> {
    Context context;
    List<Meal> mealList;

    public MealsAdapter(Context context, List<Meal> mealList) {
        this.context = context;
        this.mealList = mealList;
    }

    @NonNull
    @Override
    public MealsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View mealView = LayoutInflater.from(context)
                .inflate(R.layout.layout_meal, parent, false);
        return new MealsViewHolder(mealView);
    }

    @Override
    public void onBindViewHolder(@NonNull MealsViewHolder holder, int position) {
        holder.textViewMealName.setText(mealList.get(position).getName());
        holder.textViewMealCalories.setText(mealList.get(position).getCalories());
        holder.textViewMealProtein.setText(mealList.get(position).getProtein());
    }

    @Override
    public int getItemCount() {
        return mealList.size();
    }
}

<?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=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerViewMeals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    app:cardElevation="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textViewMealName"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="8dp"
            android:layout_weight="1"
            android:autoSizeMaxTextSize="25sp"
            android:autoSizeMinTextSize="15sp"
            android:autoSizeStepGranularity="2sp"
            android:gravity="center"
            android:maxLines="1"
            android:text="Meal Name"
            app:autoSizeTextType="uniform" />

        <TextView
            android:id="@+id/textViewMealCalories"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="000"
            android:textSize="30sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="8dp"
            android:gravity="center"
            android:text="kc"
            android:textSize="30sp" />

        <TextView
            android:id="@+id/textViewMealProtein"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="00"
            android:textSize="30sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="g"
            android:textSize="30sp" />
    </LinearLayout>

</androidx.cardview.widget.CardView>
plugins {
    id 'com.android.application'
}

android {
    namespace 'com.example.myapplication'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdk 26
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.8.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.cardview:cardview:1.0.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'

}

Errors in Android Studio

我将问题隔离到一个新的 android 项目中,因此只提供相关信息。问题仍然存在。认为 LinearLayoutManager 意味着什么所以我更改了 xml 以将 TextViews 保持在线性布局中,但仍然崩溃。

java android-recyclerview crash oncreate
© www.soinside.com 2019 - 2024. All rights reserved.