在我的应用程序中,我试图打开一个excel文件并为每行数据创建一个选项卡。打开文件并获取数据可以正常工作,但是如果我尝试添加页面,则会出现以下异常:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: dsv.testanwendung, PID: 19699
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
我已经尝试过仅在当前没有父项的情况下在instantiateItem中添加视图,但是,以某种方式,当我滑动到其页面时,该视图会立即被删除。
这是我的PagerAdapter类:
package dsv.testanwendung;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class PagerAdapterContent extends PagerAdapter {
private ArrayList<View> views = new ArrayList<View>();
@Override
public int getItemPosition(@NonNull Object object) {
int index = views.indexOf(object);
if (index == -1) {
return POSITION_NONE;
} else {
return index;
}
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View v = views.get(position);
container.addView(v);
return v;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView(views.get(position));
}
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
public int addView(View v) {
return addView(v, views.size());
}
public int addView(View v, int position) {
views.add(position, v);
notifyDataSetChanged();
return position;
}
public int removeView(ViewPager pager, View v) {
return removeView(pager, views.indexOf(v));
}
public int removeView(ViewPager pager, int position) {
pager.setAdapter(null);
views.remove(position);
pager.setAdapter(this);
return position;
}
public View getView(int position) {
return views.get(position);
}
}
这是我尝试通过主要活动添加内容的方法:
viewpageContent = findViewById(R.id.vpContent);
adapterContent = new PagerAdapterContent();
vpContent.setAdapter(adapterContent);
LayoutInflater inflater = getLayoutInflater();
FrameLayout fl = (FrameLayout)inflater.inflate(R.layout.fragment_content, null, false);
while (rowIterator.hasNext()) {
HSSFRow row = (HSSFRow)rowIterator.next();
((InputUserDefined)f).addButton(row.getCell(0).toString());
int pageIndex = adapterContent.addView(fl);
}
答案 0 :(得分:0)
使用StatePagerAdapter并更新适配器的数据调用notifyDataSetChanged方法。
答案 1 :(得分:0)
尝试
while (rowIterator.hasNext()) {
LayoutInflater inflater = getLayoutInflater();
FrameLayout fl = (FrameLayout)inflater.inflate(R.layout.fragment_content, null, false);
HSSFRow row = (HSSFRow)rowIterator.next();
((InputUserDefined)f).addButton(row.getCell(0).toString());
int pageIndex = adapterContent.addView(fl);
}