Fragment中的Gridview问题

时间:2016-05-31 10:39:19

标签: android android-fragments android-studio android-gridview

我在片段中使用gridview时,我的适配器出现了nullpointer异常。当应用程序启动时,Pager会将片段加载到选项卡中,但适配器会发送null并且应用程序会停止

在这里你可以看到我的主要活动:

public class MainLayout extends AppCompatActivity  {
ViewPager pager;
TabLayout tabLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_layout);

    pager = (ViewPager) findViewById(R.id.view_pager);
    tabLayout = (TabLayout) findViewById(R.id.tab_layout);

    // Fragment manager to add fragment in viewpager we will pass object of Fragment manager to adpater class.
    FragmentManager manager = getSupportFragmentManager();

    //object of com.example.babus.konektamos.PagerAdapter passing fragment manager object as a parameter of constructor of com.example.babus.konektamos.PagerAdapter class.
    PagerAdapter adapter = new PagerAdapter(manager);

    //set Adapter to view pager
    pager.setAdapter(adapter);

    //set tablayout with viewpager
    tabLayout.setupWithViewPager(pager);

    // adding functionality to tab and viewpager to manage each other when a page is changed or when a tab is selected
    pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    //Setting tabs from adpater
    tabLayout.setTabsFromPagerAdapter(adapter);

 }


//inicio menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.tuto:
            Intent i = new Intent(MainLayout.this, Tutorial.class);
            finish();
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }

 }
 //final menu







//modificamos el boton atras para que no nos devuelva al wizzard
@Override
public void onBackPressed(){

    finish();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}
}

在这里你可以看到我的页面适配器:

public class PagerAdapter extends FragmentStatePagerAdapter {
public PagerAdapter(FragmentManager fm) {
    super(fm);
}
@Override
public Fragment getItem(int position) {

    Fragment frag = null;
    switch (position){
        case 0:
            frag = new OfertasFragment();
            break;
        case 1:
            frag = new NegociosFragment();
            break;
        case 2:
            frag = new TarjetaFragment();
            break;
    }
    return frag;
}

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

@Override
public CharSequence getPageTitle(int position) {
    String title = " ";
    switch (position){
        case 0:
            title = "Ofertas";
            break;
        case 1:
            title = "Negocios";
            break;
        case 2:
            title = "Tarjeta";
            break;
    }

    return title;
}
}

这是片段的xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.babus.konektamos.OfertasFragment">

<!-- TODO: Update blank fragment layout -->
<GridView
    android:id="@+id/grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="120dp"
    android:horizontalSpacing="@dimen/espacio_grilla"
    android:numColumns="2"
    android:padding="@dimen/espacio_grilla"
    android:verticalSpacing="@dimen/espacio_grilla" />

在这里你可以看到我的片段:

public class OfertasFragment extends Fragment implements AdapterView.OnItemClickListener{
private GridView gridView;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //inicio gridview
    gridView = (GridView) this.getActivity().findViewById(R.id.grid);
    gridView.setAdapter(new AdaptadorDeCupones(this.getActivity()));
    gridView.setOnItemClickListener(this);
    //fin gridview
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_ofertas,container,false);
    return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}




//Inicio detalle cupones
//@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    cupones item = (cupones) parent.getItemAtPosition(position);

    Intent intent = new Intent(this.getActivity(), ActividadDetalle.class);
    intent.putExtra(ActividadDetalle.EXTRA_PARAM_ID, item.getId());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        ActivityOptionsCompat activityOptions =
                ActivityOptionsCompat.makeSceneTransitionAnimation(
                        this.getActivity(),
                        new Pair<View, String>(view.findViewById(R.id.imagen_cupon),
                                ActividadDetalle.VIEW_NAME_HEADER_IMAGE)
                );

        ActivityCompat.startActivity(this.getActivity(), intent, activityOptions.toBundle());
    } else
        startActivity(intent);
}
//final detalle cupones


}

2 个答案:

答案 0 :(得分:2)

将以下代码添加到您的onCreateView方法中,并从onCreate方法

中删除代码
@Override
public View onCreateView(
    LayoutInflater inflater, 
    ViewGroup container,
    Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_ofertas,container,false);

    //inicio gridview
    gridView = (GridView) view.findViewById(R.id.grid);
    gridView.setAdapter(new AdaptadorDeCupones(this.getActivity()));
    gridView.setOnItemClickListener(this);

    return view;
}

答案 1 :(得分:2)

片段在onCreateView中加载其布局,并在调用onViewCreated时完成加载。

您需要在其中任何一个中找到您的布局,引用夸大的View。目前,Android会在GridView中查找您的MainActivity,并返回null,因为没有GridView

//view is your inflated view in onCreateView or the view passed in onViewCreated
gridView = (GridView) view.findViewById(R.id.grid);
gridView.setAdapter(new AdaptadorDeCupones(this.getActivity()));
gridView.setOnItemClickListener(this);