mynamecsl 2018-04-12 16:49 采纳率: 58%
浏览 712
已采纳

想把GridView添加到ViewPager里面。加载无效

用TabLayout和ViewPager关联后,想把GridView添加到ViewPager里面。报空指针异常。

上面那个问题解决了,没有加载layout所以空对象。
View view = this.getLayoutInflater().inflate(R.layout.grid_view,null);
现在不报错,但是GridView没有加载进来,各位大神帮忙看一下是不是适配器写错了图片说明

04-12 08:39:37.363 25278-25278/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chenshenglei.tablayouttest, PID: 25278
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chenshenglei.tablayouttest/com.example.chenshenglei.tablayouttest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.chenshenglei.tablayouttest.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)

下面贴代码MyGridViewAdapter.java

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import java.util.List;
import java.util.Map;

/**
 * Created by chenshenglei on 18-4-12.
 */

public class MyGridViewAdapter extends SimpleAdapter {

    private Context mContext;

    public MyGridViewAdapter(Context context, List<Map<String, Object>> dataLists, int layout, String[] key, int[] item){
        super(context, dataLists,layout, key, item);
        this.mContext = context;

    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = super.getView(position, convertView, parent);

        return convertView;
    }

}

代码TabPagerAdapter.java

package com.example.chenshenglei.tablayouttest;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;

import java.security.PublicKey;
import java.util.List;

/**
 * Created by chenshenglei on 18-4-12.
 */

//自定义ViewPager页面适配器
public  class TabPagerAdapter extends PagerAdapter {

    private Context mContext;
    private String[] mTitleArray;
    private List<GridView> mList;

    public TabPagerAdapter (Context context, String[] title) {
        super();
        this.mContext = context;
        this.mTitleArray = title;
    }

    public TabPagerAdapter (Context context, String[] title, List<GridView> array) {
        super();
        this.mContext = context;
        this.mTitleArray = title;
        this.mList = array;
    }

    @Override
    public int getCount() {
        return mTitleArray.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = mList.get(position);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }


    @Override
    public CharSequence getPageTitle(int position) {
        return mTitleArray[position];
    }

}

代码 MainActivity.java
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

private TabLayout mTabLayout;
private ViewPager mViewPager;
private String[] mTitleArray = {"酒标","葡萄品种"};

private GridView gridView1;
private GridView gridView2;

private MyGridViewAdapter myGridViewAdapter;
private List<GridView> mList;

private List<Map<String, Object>> dataList;
private List<Map<String, Object>> dataList2;

private int[] img = {R.mipmap.ic_launcher_round,R.mipmap.ic_launcher};
private int[] img2 = {R.mipmap.ic_launcher_round,R.mipmap.ic_launcher};
private  String[] imgName = {"1","2"};
private  String[] imgName2 = {"3","4"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_weibo_timeline);

    gridView1 = (GridView)findViewById(R.id.grid_test);
    dataList = new ArrayList<Map<String, Object>>();
    myGridViewAdapter = new MyGridViewAdapter(this,
            getData(), R.layout.grid_item,
            new String[] {"img", "txt"},
            new int[] {R.id.img_item,R.id.txt_item});
    gridView1.setAdapter(myGridViewAdapter);

    gridView2 = (GridView)findViewById(R.id.grid_test);
    dataList2 = new ArrayList<Map<String, Object>>();
    myGridViewAdapter = new MyGridViewAdapter(this,
            getData2(), R.layout.grid_item,
            new String[] {"img", "txt"},
            new int[] {R.id.img_item,R.id.txt_item});
    gridView2.setAdapter(myGridViewAdapter);
    mList = new ArrayList<GridView>();
    mList.add(gridView1);
    mList.add(gridView2);


    mViewPager = (ViewPager) findViewById(R.id.view);
    TabPagerAdapter adapter = new TabPagerAdapter(getApplicationContext(),mTitleArray,mList);
    mViewPager.setAdapter(adapter);

    mTabLayout = (TabLayout) findViewById(R.id.tab);
    mTabLayout.setupWithViewPager(mViewPager);

}

private List<Map<String,Object>> getData() {
    for (int i=0; i<img.length; i++) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("img", img[i]);
        map.put("txt", imgName[i]);
        dataList.add(map);
    }

    return dataList;
}

private List<Map<String,Object>> getData2() {
    for (int i=0; i<img.length; i++) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("img", img2[i]);
        map.put("txt", imgName2[i]);
        dataList2.add(map);
    }

    return dataList2;
}

}

grid_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:id="@+id/grid_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numColumns="4"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="5dp"
        android:layout_marginTop="40dp"/>
</LinearLayout>


grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="#ffffff">

    <ImageView
        android:id="@+id/img_item"
        android:src="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txt_item"
        android:textColor="#000000"
        android:text="文字区域"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>```


activity_weibo_timeline.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <android.support.v4.view.ViewPager
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"/>
    </LinearLayout>

</LinearLayout>


  • 写回答

9条回答 默认 最新

  • ChinaDragonDreamer 全栈领域新星创作者 2018-04-13 15:43
    关注

    建议将 grid_view.xml 替换成下面的
    android:id="@+id/grid_test"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="4"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    >

    代码里:

    gridView1 = (GridView) this.getLayoutInflater().inflate(R.layout.grid_view,null);
    gridView2 = (GridView) this.getLayoutInflater().inflate(R.layout.grid_view,null);

    方法一:

    public class MyGridViewAdapter extends SimpleAdapter {

    private Context mContext;
    private List<Map<String, Object>> mMataLists;
    
    public MyGridViewAdapter(Context context, List<Map<String, Object>> dataLists, int layout, String[] key, int[] item){
        super(context, dataLists,layout, key, item);
        this.mContext = context;
         this.mMataLists = dataLists == null ? new ArrayList<Map<String, Object>>() : dataLists;
    
    }
    
    @Override
    public int getCount() {
        return mMataLists.size();
    }
    

    // 下面方法代码不变,不粘贴了

    }

    方法二:
    直接使用 SimpleAdapter;

    private SimpleAdapter myGridViewAdapter;

    myGridViewAdapter = new SimpleAdapter(MainActivity.this,
    getData(), R.layout.grid_item,
    new String[] {"img", "txt"},
    new int[] {R.id.img_item,R.id.txt_item});
    gridView1.setAdapter(myGridViewAdapter);

    这样可以正常显示了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里