当前位置: 首页 > 知识库问答 >
问题:

'booleanandroid.support.v7.widget.RecyclView$LayoutManager.canScroll垂直()'

屈升
2023-03-14

当我尝试使用RecyclerView时,如何解决我的问题。当我添加两行代码时

recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

我的代码总是显示错误

06-22 19:52:25.801 19743-19743/com.transvision.bertho.transvisiondashboardapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.transvision.bertho.transvisiondashboardapp, PID: 19743
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.transvision.bertho.transvisiondashboardapp/com.transvision.bertho.transvisiondashboardapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
at com.transvision.bertho.transvisiondashboardapp.MainActivity.onCreate(MainActivity.java:53)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

如何解决我的问题?它看起来像是<代码>回收视图。setLayoutManager但我无法单独解决我的问题。

这是我的代码(ChannelAdapter.java)

package adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.transvision.bertho.transvisiondashboardapp.R;

import java.util.List;

import model.Channel;


public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder> {

    private List<Channel> channels;
    private int rowLayout;
    private Context context;

    public static class ChannelViewHolder extends RecyclerView.ViewHolder {

        LinearLayout moviesLayout;
        TextView movieTitle;
        TextView data;
        TextView movieDescription;
        TextView rating;

        TextView name;
        TextView code;
        TextView description;
        TextView number;
        TextView definition;
        TextView paket;
        ImageView logo;

        public ChannelViewHolder(View v) {
            super(v);
            moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
            name = (TextView) v.findViewById(R.id.title);
            definition = (TextView) v.findViewById(R.id.subtitle);
            description = (TextView) v.findViewById(R.id.description);
//            rating = (TextView) v.findViewById(R.id.rating);
        }
    }

    public ChannelAdapter(List<Channel> channels, int rowLayout, Context context) {
        this.channels = channels;
        this.rowLayout = rowLayout;
        this.context = context;
    }

    @Override
    public ChannelAdapter.ChannelViewHolder onCreateViewHolder(ViewGroup parent,
                                                            int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
        return new ChannelViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ChannelViewHolder holder, final int position) {
        holder.name.setText(channels.get(position).getName());
        holder.definition.setText(channels.get(position).getDefinition());
        holder.description.setText(channels.get(position).getDescription());
//        holder.rating.setText(channels.get(position).getVoteAverage().toString());
    }

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

}

主要活动。xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

app_bar_main。xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="com.transvision.bertho.transvisiondashboardapp.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

主要的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

你回家了。xml

<RelativeLayout 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"
    android:orientation="vertical"
    tools:context="com.transvision.bertho.transvisiondashboardapp.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/movies_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</RelativeLayout>

还有我的ctivity.java

package com.transvision.bertho.transvisiondashboardapp;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import java.util.List;

import adapter.ChannelAdapter;
import model.Channel;
import model.ChannelResponse;
import model.Movie;
import model.MoviesResponse;
import page.DefaultFragment;
import page.HomeFragment;
import page.ProfileFragment;
import rest.ApiClient;
import rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private final static String API_KEY = "7e8f60e325cd06e164799af1e317d7a7";

    private RecyclerView recyclerView;

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

        recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Fragment fragment = null;
        fragment = new DefaultFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.root, fragment);
        fragmentTransaction.commit();

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        Fragment fragment = null;
        String title = getString(R.string.app_name);

        if (id == R.id.nav_camera) {
            fragment = new HomeFragment();
            title = "Home";
            getChannelData();
        } else if (id == R.id.nav_gallery) {
            fragment = new ProfileFragment();
            title = "Profile";
        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.root, fragment);
            fragmentTransaction.commit();

            // set the toolbar title
            getSupportActionBar().setTitle(title);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void getChannelData() {
        ApiInterface apiService = ApiClient.getChannel().create(ApiInterface.class);
        Call<ChannelResponse> call = apiService.getItems();

        call.enqueue(new Callback<ChannelResponse>() {
            @Override
            public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
                int statusCode = response.code();
                List<Channel> channel = response.body().getItems();
                Log.d(TAG, "NUMBER OF MOVIES RECEIVED : " + channel.size());
                recyclerView.setAdapter(new ChannelAdapter(channel, R.layout.list_channel, getApplicationContext()));
            }

            @Override
            public void onFailure(Call<ChannelResponse> call, Throwable t) {
                // Log error here since request failed
                Log.e(TAG, t.toString());
            }
        });
    }


    public void showToast(String output){
        Toast.makeText(this.getBaseContext(), output, Toast.LENGTH_SHORT).show();
    }
}

也许我忘记换东西了,请帮忙。。。

谢谢

共有3个答案

海雪松
2023-03-14
匿名用户

要么移动fragment_回家。xmlmain中的代码。xml文件,如果您想在活动中查看recyclerView。即

主要的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v7.widget.RecyclerView
    android:id="@+id/movies_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical" />

</FrameLayout>

</LinearLayout>

在你的活动中添加一个片段,它会将片段充气回家。xml并将回收视图初始化代码移动到您的片段。i、 e.在你的片段中有以下代码:

recyclerView = (RecyclerView) rootview.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

钱建本
2023-03-14
recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
// The above line doesnot throw null pointer exception, since you can cast null to any object. Refer this post - http://stackoverflow.com/questions/18723596/no-exception-while-type-casting-with-a-null-in-java
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// The above line will throw null pointer exception, since here we are accessing the null object and invoking a method on that null object.

这样做可以避免空指针异常

 recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
 if(recyclerView != null) {     
     recyclerView.setLayoutManager(new LinearLayoutManager(this));
     .....
     .....
     .....
 }
陈法
2023-03-14

您的recyclerView为空。因为只有当fragment\u home时才会添加RecyclerView。xml已加载到您的活动中。

这意味着它已经准备好了(假设你的DefaultFraank是膨胀的fragment_home.xml

Fragment fragment = null;
fragment = new DefaultFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();

你应该在那之后做findViewById。然而,fragmentTransaction。提交() 是一个异步进程。之后可能无法立即获得片段内容。因此,您需要调用fragmentTransaction。commitNow()以确保将片段添加到活动中。

recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

从活动级别查找片段的视图不是一个好主意。其中一个原因是避免像您现在面临的情况,因为片段内容在活动中无法得到保证。

更好的方法是在片段onViewCreated

如果您的数据是从活动中获取的,您仍然可以将数据传递给活动中的片段。

参见“片段和活动之间的交流”等主题https://developer.android.com/training/basics/fragments/communicating.html

 类似资料:
  • 我对Vert.x非常陌生,就像几天前一样。我来自一个JAX式的,安逸的世界。我可能大错特错,请指正。 我的问题是:如何使顶点公开自己的REST接口(子路由器),以及如何将其子路由器注册到应用程序的主路由器中? 我尝试过类似的东西,但是当我请求/产品/所有:( } }

  • 垂直对齐 1. grid-template-areas 属性值保持换行,并使用空格保持每列垂直对齐。 例如: .foo { grid-template-areas: "header header" "nav main" "footer ...."; } 2. grid、grid-template

  • 提示 页面模板源码免费开源,在uni-app的插件市场uView的 示例项目 中,在右上角选择"使用 HBuilderX 导入示例项目" 或者 "下载示例项目ZIP", 在HX运行项目即可看到和使用模板。 uView为用户制作了两个类型的分类页面,分别是左右联动,左右分开的场景。 这两个页面,为布局而非组件形式,可以根据自己的需求修改页面的结构,逻辑,样式。 左右联动 该场景左右可以联动,右边所有

  • 问题内容: 我在浮动div中有一个img,但我不知道如何垂直居中。 垂直对齐:当然中间不起作用。 问题答案: 要在父元素中垂直对齐文本,并谨记的是一个内联元素等行为 类似 文本,你可以简单地设置到父元素: 。

  • 问题内容: 我怎么能垂直居中内的? 到目前为止,我的代码: 我已经尝试过“ top:50%”;和“ vertical-align:middle”;没有成功 编辑: 好的,所以已经讨论了很多。我也许已经开始了另一场小型的火焰战争。但是为了论证,那我该如何用一个表呢?到目前为止,我已经将CSS用于其他所有内容,所以这并不是说我没有尝试采用“良好做法”。 编辑: 内部div没有固定的高度 问题答案: 简

  • 我被vertx实例搞糊涂了。第一次看到文档时,我认为实例意味着事件循环线程的数量 当我深入研究源代码(vertx 2.1.2)时,我发现verticle实例意味着事件循环线程组中的一项任务。事件循环线程总是等待选择器并运行任务。 在vertx中有必要有顶点实例吗?因为顶点只由一个事件循环运行一次。更准确地说,事件循环线程运行Verentlestart方法并将其丢弃,它就像一个条目一样工作,仅此而已