问题描述
- 【Android】ViewPager+GridView结合使用报错?
- 首先声明下程序是可运行的代码,运用一个initViewPager();方法初始化ViewPager和GridView。我想把初始化GridView初始化放在initGridView中该如何写这部分代码。因为XML文件无错所以就不上了,JAVA代码如下。
public class MainActivity extends Activity { private View tab01 = null; private View tab02 = null; private ViewPager mViewPager = null; private List<View> tabList = null; private PagerAdapter mAdapter = null; private GridView mGridView = null; private List<Map<StringObject>> mData = new ArrayList<Map<StringObject>>(); private SimpleAdapter gAdapter = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViewPager();// initGridView(); } private void initGridView() { } private List<Map<String Object>> getData() { int[] image = {R.drawable.icon_clouddayR.drawable.icon_fog R.drawable.icon_rainR.drawable.icon_snowR.drawable.icon_sunnyday}; String[] name = {""图一""图二""图三""图四""图五""}; for(int i=0;i<name.length;i++){ Map<StringObject> map = new HashMap<StringObject>(); map.put(""image"" image[i]); map.put(""name"" name[i]); mData.add(map); } return mData; } private void initViewPager() { this.mViewPager = (ViewPager) findViewById(R.id.mViewPager); LayoutInflater mInlfater = getLayoutInflater(); this.tab01 = mInlfater.inflate(R.layout.tab01 null); this.tab02 = mInlfater.inflate(R.layout.tab02 null); this.tabList = new ArrayList<View>(); tabList.add(tab01); tabList.add(tab02); mAdapter = new PagerAdapter() { @Override public boolean isViewFromObject(View arg0 Object arg1) { // TODO Auto-generated method stub return arg0 == arg1; } @Override public int getCount() { // TODO Auto-generated method stub return tabList.size(); } @Override public void destroyItem(ViewGroup container int position Object object) { // TODO Auto-generated method stub container.removeView(tabList.get(position)); } @Override public Object instantiateItem(ViewGroup container int position) { // TODO Auto-generated method stub container.addView(tabList.get(position)); return tabList.get(position); } }; mViewPager.setAdapter(mAdapter); //--------↓ this.mGridView = (GridView)tab02.findViewById(R.id.mGridView); this.gAdapter = new SimpleAdapter(this getData()R.layout.griditem new String[] {""image""name""}new int[] {R.id.imageR.id.name}); this.mGridView.setAdapter(gAdapter); //--------↑ //以上代码是否可以放在initGridView()中实现,有待考证。 }}
如代码所示
解决方案
Android - Fragment+ViewPager结合使用
android控件篇:ViewPager+Fragment+GridView的使用(与AndroidQuery框架结合)
Android结合fragment灵活使用ViewPager
解决方案二:
可以,保证方法调用先后顺序,放进去调试一下即可。
时间: 2024-10-27 16:53:16