【问题标题】:RecyclerView No adapter attachedRecyclerView 未连接适配器
【发布时间】:2023-03-08 13:02:01
【问题描述】:

有一个带有片段容器的活动,它在活动开始时添加了 ViewPagerFragment。 MainFragment(即选项卡)内有一个 RecyclerView,它显示但未填充数据。 尝试将宽度和高度从 0 更改为 Match_Parent 和 Fixed_Size。还将 ConstraintLayout 更改为 RelativeLayout.Using 主题android:theme="@style/MyMaterialTheme" 样式.xml

<style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
</style>

E/RecyclerView:没有附加适配器;跳过

MainActivity.class 公共类 MainActivity 扩展 AppCompatActivity {

private static final String TAG = "MainActivity";
private AdView mAdView;
private FragmentTransaction mFragmentTransaction;


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


    mAdView = (AdView) findViewById(R.id.adView);

    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
    mAdView.loadAd(adRequest);

    mFragmentTransaction = getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.container_frame, new ViewPagerFragment());
    mFragmentTransaction.commit();

}

@Override
protected void onResume() {
    super.onResume();
    mAdView.resume();
}

@Override
protected void onPause() {
    super.onPause();
    mAdView.pause();
}

@Override
protected void onDestroy() {
    mAdView.destroy();
    super.onDestroy();
}

activity_main.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                         xmlns:tools="http://schemas.android.com/tools"
                                         xmlns:ads="http://schemas.android.com/apk/res-auto"
                                         xmlns:app="http://schemas.android.com/apk/res-auto"
                                         android:layout_width="match_parent"
                                         android:layout_height="match_parent"
                                         android:background="@color/colorPrimaryDark"
                                         tools:context="com.newakkoff.justad.Activities.MainActivity">

<RelativeLayout
    ads:layout_constraintBottom_toTopOf="@+id/adView"
    ads:layout_constraintTop_toTopOf="parent"
    ads:layout_constraintLeft_toLeftOf="parent"
    ads:layout_constraintRight_toRightOf="parent"
    android:id="@+id/container_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</RelativeLayout>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="0dp"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintLeft_creator="1"
    android:layout_height="50dp">
</com.google.android.gms.ads.AdView>
</android.support.constraint.ConstraintLayout>

ViewPagerFragment.class

public class ViewPagerFragment extends Fragment {

private ViewPager mViewPager;
private Toolbar mToolbar;
private TabLayout mTableLayout;
int i = 1;



@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_view_pager, container, false) ;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);

    ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);



    mViewPager = (ViewPager) view.findViewById(R.id.view_pager_main);
    mViewPager.setAdapter(new CustomPagerAdapter(getActivity()));
    mViewPager.setCurrentItem(1);

    mTableLayout = (TabLayout) view.findViewById(R.id.tabs);
    mTableLayout.setupWithViewPager(mViewPager);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_main, menu);
    super.onCreateOptionsMenu(menu, inflater);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}

fragment_view_pager.xml

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

<android.support.design.widget.AppBarLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:id="@+id/appBarLayout"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"

        />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />

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

<android.support.v4.view.ViewPager
android:id="@+id/view_pager_main"
app:layout_constraintTop_toBottomOf="@+id/appBarLayout"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="0dp"
android:layout_height="0dp">

MainFragment.class

public class MainFragment extends Fragment {


private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private LinearLayoutManager mLayoutManager;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     mLayoutManager = new LinearLayoutManager(this.getActivity(),LinearLayoutManager.VERTICAL,false);
    mAdapter = new MyAdapter(new String[]{"test one", "test two", "test three", "test four", "test five", "test six", "test seven"});
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_recycler_view);
  mRecyclerView.setHasFixedSize(true);
   mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mAdapter);

    return view;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

fragment_main.xml

<?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.v7.widget.RecyclerView
    android:id="@+id/rv_recycler_view"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="8dp"
    android:layout_marginEnd="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    tools:listitem="@layout/card_item"
    android:background="@color/colorPrimary"/>
 </android.support.constraint.ConstraintLayout>

CustomPageAdapter.class

public class CustomPagerAdapter extends PagerAdapter {

private Context mContext;

public CustomPagerAdapter(Context context) {
    mContext = context;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ModelPager modelsPager = ModelPager.values()[position];
    LayoutInflater inflater = LayoutInflater.from(mContext);
    ViewGroup layout = (ViewGroup) inflater.inflate(modelsPager.getLayoutResId(), container, false);
    container.addView(layout);
    return layout;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
}

@Override
public int getCount() {
    return ModelPager.values().length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}


@Override
public CharSequence getPageTitle(int position) {
    ModelPager customPagerEnum = ModelPager.values()[position];
    return mContext.getString(customPagerEnum.getTitleResId());
}
}

ModelPager.class

public enum ModelPager {
SEND_FRAGMENT(R.string.send_fragment_tab,R.layout.fragment_send),
MAIN_FRAGMENT(R.string.main_fragment_tab, R.layout.fragment_main),
ABOUT_FRAGMENT(R.string.about_fragment_tab, R.layout.fragment_about);

private int mTitleResId;
private int mLayoutResId;

ModelPager(int titleResId, int layoutResId) {
    mTitleResId = titleResId;
    mLayoutResId = layoutResId;
}

public int getTitleResId() {
    return mTitleResId;
}

public int getLayoutResId() {
    return mLayoutResId;
}
}

MyAdapter.class

      public  class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private String[] mDataset;


    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    static class MyViewHolder extends RecyclerView.ViewHolder {
        private static final String TAG = "My Recycler Adapter";
        CardView mCardView;
        TextView mTextView;

        MyViewHolder(View v) {
            super(v);

            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
                }
            });
            mCardView = (CardView) v.findViewById(R.id.card_view);
            mTextView = (TextView) v.findViewById(R.id.tv_text);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter( String[] myDataset) {

         mDataset = myDataset;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_item, parent, false);
        // set the view's size, margins, paddings and layout parameters
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.mTextView.setText(mDataset[position]);
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

card_item.xml

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

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_margin="10dp"
    android:layout_height="62dp"
    card_view:cardCornerRadius="4dp"
    card_view:elevation="14dp">

        <TextView
            android:id="@+id/tv_text"
             android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:gravity="center" >
        </TextView>


</android.support.v7.widget.CardView>

</RelativeLayout>

【问题讨论】:

  • 你能把CustomPAgerAdapter的代码贴出来吗?
  • @VeneetReddy 已添加,您可以查看一下吗?
  • 为什么要将RecyclerView layout_heightlayout_width设置为0dp?
  • 顺便说一句,您的应用程序是否因此而崩溃?通常不会,RecyclerView 只是被忽略..
  • @VeneetReddy 我使用 ConstraintLayout,并且使用 0dp(任何大小)代替 Match_Parent

标签: java android android-viewpager android-recyclerview


【解决方案1】:

在逻辑上与该错误有任何关系的唯一地方是 mRecyclerView.setAdapter(mAdapter);,因为它是唯一的 RecyclerView。

看文档mAdapter是允许null代表没有适配器的。因此,该变量要么是null,要么没有正确实现RecyclerView.Adapter 接口。

【讨论】:

猜你喜欢
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
相关资源
最近更新 更多