Fragmnet中RecyclerView中的项目不会出现

时间:2018-06-29 16:25:06

标签: android android-fragments android-recyclerview

我看到有类似的帖子,但是我的代码与解决方案中的代码相同,因此它们在我的案例中没有用。我的应用程序启动,但显示两个选项卡。但是应该显示其中一个RecyclerView项的项是空的。我也收到此错误:

E/RecyclerView: No adapter attached; skipping layout

所以我有一个带有TabLayout和ViewPager的活动

    public class MainActivity extends AppCompatActivity {
    TabLayout tabLayout;
    ViewPager viewPager;
    PagerAdapter pagerAdapter;

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

        tabLayout=findViewById(R.id.tab_layout);
        viewPager=findViewById(R.id.view_pager);

        tabLayout.addTab(tabLayout.newTab().setText("CitiesFragment"));
        tabLayout.addTab(tabLayout.newTab().setText("My CitiesFragment"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        pagerAdapter=new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(pagerAdapter);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

这是一个只有RecyclerView的片段

    public class CitiesFragment extends Fragment {
    RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View itemView = inflater.inflate(R.layout.cities_layout, container, false);
        recyclerView = itemView.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        List<City> data = Database.getDatabase();
        CitiesAdapter adapter = new CitiesAdapter(data);
        recyclerView.setAdapter(adapter);
        return itemView;
    }
}

这是片段的XML

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>
</LinearLayout>

这是适配器

    public class CitiesAdapter extends RecyclerView.Adapter<CitiesVIewHolder> {
    List<City> data;
    private int itemCount;

    public CitiesAdapter(List<City> data) {
        this.data = data;
        itemCount=data.size();
    }

    @NonNull
    @Override
    public CitiesVIewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.city_layout, viewGroup, false);
        CitiesVIewHolder viewHolder = new CitiesVIewHolder(itemView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull CitiesVIewHolder citiesVIewHolder, int position) {
        City city = data.get(position);
        citiesVIewHolder.txtCityName.setText(city.getCityName());
        citiesVIewHolder.txtCityInfo.setText(city.getCityInfo());
        LoadImageTask loadImageTask = new LoadImageTask(citiesVIewHolder.imgCity);
        loadImageTask.execute(city.getImageUrl());
    }

    @Override
    public int getItemCount() {
        return itemCount;
    }
}

以及适配器的XML

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

        <ImageView
            android:id="@+id/img_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txt_city_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txt_city_info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />


</LinearLayout>

我的PagerAdapter仅返回两个片段之一(其中一个当前为空,另一个在RecyclerView上)

public class PagerAdapter extends FragmentStatePagerAdapter {
    private int itemCount;

    public PagerAdapter(FragmentManager fm, int itemCount) {
        super(fm);
        this.itemCount = itemCount;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new CitiesFragment();
            case 1:
                return new MyCitiesFragment();
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return itemCount;
    }
}

对代码重载感到抱歉,但我真的不明白我在做什么错。感谢您的提前帮助。

3 个答案:

答案 0 :(得分:0)

首先,适配器xml的根LinearLayout的高度设置为match_parent,因此将其更改为wrap_content

第二个override onViewCreated并在recyclerView中设置onCreateView。例如:

 @Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    recyclerView = view.findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setHasFixedSize(true);
    List<City> data = Database.getDatabase();
    CitiesAdapter adapter = new CitiesAdapter(data);
    recyclerView.setAdapter(adapter);
 }

还可以考虑添加以下行:recyclerView.setHasFixedSize(true);

答案 1 :(得分:0)

  

E / RecyclerView:未连接适配器;跳过布局

  • TabLayout使用recyclerView显示片段,但是片段需要花费更多的时间来加载数据源,从而使得在没有连接适配器的情况下创建回收站。

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View itemView = inflater.inflate(R.layout.cities_layout, container, false);
        recyclerView = itemView.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        // List<City> data = Database.getDatabase(); // Don't fetch data on Main (UI) Thread 
        CitiesAdapter adapter = new CitiesAdapter(new ArrayList<City>()); // 
        recyclerView.setAdapter(adapter);
        // Display city here one background and then update adapter.
        return itemView;
    }
    
  • 如果数据源从本地数据库获取数据,则您可以在handler上使用postDelayRecyclerView

    recyclerView.postDelay(new Runnable(){
      public void run(){
        adapter.setCityList(result);
      }
    },500);
    
  • 如果使用使用后台任务加载服务器数据源的数据,则可以检查此answer以便从服务器中顺利获取数据。

//在异步任务中加载数据源。

new AsyncTaskHandler(new OnFinishCallback() {
    @Override
    public void onSuccess(List<City> result) {
        adapter.setCityList(result);
    }
}).execute("param that need to load datasource");

答案 2 :(得分:0)

  • 我已经创建了一个简单的应用程序来模拟您的情况。
  • RecyclerView的宽度必须为match_partent

    <!--RecyclerView width must be match_parent-->
    <android.support.v7.widget.RecyclerView
      android:id="@+id/recycler_view"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
    
  • 您可以在 Github

  • 上找到完整的sample/CityPreview应用

enter image description here