我正在尝试使用RecyclerView在Android上启用连续滚动但是我遇到并且错误“指定的孩子已经有父。在使用片段时,必须首先在孩子的父母上调用removeView()”。当我在一个活动上运行相同的代码时,它可以完美地运行。以下是我的代码:
public class TestFragment extends Fragment {
private HashMap loc = new HashMap();
private ArrayList<String> orderNumber = new ArrayList<>(),
items = new ArrayList<>(), location = new ArrayList<>();
private RelativeLayout fragmentContainer;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private ProgressBar progressBar;
private List<String> mStringList;
private int mLoadedItems = 0;
private SampleAdapter mSampleAdapter;
private MainActivityBinding mActivityMainBinding;
public static TestFragment newInstance() {
TestFragment fragment = new TestFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mActivityMainBinding = DataBindingUtil.setContentView(getActivity(), R.layout.main_activity);
View view = mActivityMainBinding.getRoot();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mActivityMainBinding.recyclerView.setLayoutManager(linearLayoutManager);
mActivityMainBinding.recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
mStringList = new ArrayList<>();
mSampleAdapter = new SampleAdapter(mStringList);
mActivityMainBinding.recyclerView.setAdapter(mSampleAdapter);
addDataToList();
mActivityMainBinding.recyclerView.addOnScrollListener(onScrollListener);
return view;
}
private final RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(final RecyclerView recyclerView, final int newState) {
}
@Override
public void onScrolled(final RecyclerView recyclerView, final int dx, final int dy) {
addDataToList();
}
};
private void addDataToList() {
mActivityMainBinding.itemProgressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 30; i++) {
mStringList.add("SampleText : " + mLoadedItems);
mLoadedItems++;
}
mSampleAdapter.notifyDataSetChanged();
mActivityMainBinding.itemProgressBar.setVisibility(View.GONE);
}
}, 1500);
}
}