我有一个ViewPager,有4页。所有片段内容都是动态创建的,其中包含一些TextView和ImageView。所有页面都创建得很好。但是,如果我尝试通过触摸TextView来刷页面,应用程序会在三星Galaxy S4 - OS V4.4.2单独下面的日志中崩溃。
我已经在LG Nexus5-OS V5.1和三星Galaxy NoteII-OS V4.3上进行了测试。即使我触摸TextView并滑动页面,应用程序也能正常工作。
Exception in MessageQueue callback: handleReceiveCallback
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1016)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:545)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:251)
at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1849)
at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:1984)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2043)
下面是我的片段代码。
public class HorizontalSwipPage extends Fragment {
private View mPage = null;
LinearLayout root = null;
public void setArguments(View page) {
mPage = page;
}
public HorizontalSwipPage() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = null;
root = new LinearLayout(getActivity());
root.removeAllViews();
root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT));
root.addView(mPage);
return root;
}
@Override
public void onDestroyView() {
// TODO Auto-generated method stub
root.removeAllViews();
root = null;
super.onDestroyView();
}
}
此处 mPage 是动态创建的布局视图。 下面是我的适配器代码。
public class TestPagerAdapter extends FragmentStatePagerAdapter implements
IconPagerAdapter {
public int noOfPages = 0;
private View[] PageList = null;
public TestPagerAdapter(Context context, FragmentManager fm,
int pNoOfPages) {
super(fm);
noOfPages = pNoOfPages;
PageList = new View[noOfPages];
}
public void addPage(View grid, int index) {
PageList[index] = grid;
}
@Override
public Fragment getItem(int position) {
HorizontalSwipPage f = new HorizontalSwipPage();
f.setArguments(PageList[position]);
return f;
}
@Override
public int getCount() {
return noOfPages;
}
}
请有人帮我解决这个问题。
答案 0 :(得分:2)
java.lang.ClassCastException:无法转换android.widget.TextView 到android.view.ViewGroup
当您尝试将类从一种类型不正确地转换为另一种类型时,这是Java程序中可能发生的异常。
我认为您缺少设置 TextView
正确ID 。