我需要在一个Fragment中以编程方式添加多个RecyclerView。我已经成功地包含了一个使用xml布局的RecyclerView(如下所示),它工作得很好,但是当我尝试以编程方式添加任何一个RecyclerView时,即使返回的RecyclerView不为null,也没有一个出现在片段视图中。因为我的数据源是Web API驱动的,所以我无法在xml布局中添加特定数量的RecyclerView,因为所需数量会随时改变,因此必须在程序中完成。我尝试了许多不同的方法,但所有结果都是相同的,例如:没有一个RecyclerView。我还需要在每个RecyclerView上方添加TextView作为标题,我已经完成了这些并且它们完美地工作,但是它们从下面的代码中删除,以便更容易理解。我只需要能够添加多个RecyclerView就可以完成我的项目。希望有人能帮忙?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
svv = new ScrollView(getActivity());
svv.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT, ScrollView.LayoutParams.WRAP_CONTENT));
linLayout = new LinearLayout(getActivity());
linLayout.setOrientation(LinearLayout.VERTICAL);
linLayoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
View rootView = inflater.inflate(R.layout.fragment_root, container, false);
HorizontalScrollView svh;
RecyclerView itemsListing;
int top = 100;
for(int i = 0; i < itemCount; i++) {
String strSubURL = myListItem.myListUrls.get(i).toString();
sharedData.setCurrMyURL(String.valueOf(strSubURL));
// Below is where the problems start
// This works fine but only provides one recyclerview
//itemsListing = (RecyclerView) rootView.findViewById(R.id.items_listing);
// This does not work at all, showing zero recyclerviews even though the views are not null and are therefore actually created
itemsListing = new RecyclerView(inflater.getContext());
itemsListing.setPadding(0, top, 0, 0);
mLayoutManager = new LinearLayoutManager(itemsListing.getContext(), LinearLayoutManager.HORIZONTAL, false);
itemsListing.setLayoutManager(mLayoutManager);
mAdapter = new ItemsListingAdapter(mItems, this);
itemsListing.setAdapter(mAdapter);
svh = new HorizontalScrollView(getActivity());
svh.setPadding(0, top, 0, 0);
top=top+400;
}
svv.addView(linLayout);
RelativeLayout mainLayout = (RelativeLayout) rootView.findViewById(R.id.item_layout);
mainLayout.addView(svv);
return rootView;
}
XML布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/item_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#000000"
tools:context="com.myco.myapp.items.listing.ItemsListingListingFragment">
<android.support.v7.widget.RecyclerView
android:id="@+id/items_listing"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>