选项卡式活动

时间:2016-01-22 11:30:10

标签: java android android-fragments gridview tabbed

我是Java和Android Studio的初学者,我正在尝试通过以下在线教程构建应用程序。一切都很好,直到我到达标签活动。我的应用程序将有一个主要活动和树标签关联" FIRST WORDS"(只有一些文字描述应用程序)," WORDS"(将有一个网格视图)和& #34; GAMES"(里面也会有一个网格视图)。两个GridView都将导致项目点击的其他活动。     管理完成所有事情,直到我必须在第二个选项卡中引入GridView。我在xml中编写它我在.MainActivity.java中编写代码,代码上没有错误,但是当我尝试运行应用程序时它会崩溃

"无法启动活动ComponentInfo {com.gadgetcatch.firstwords / com.gadgetcatch.firstwords.MainActivity}:java.lang.NullPointerException:尝试调用虚拟方法' void android.widget.GridView。 setAdapter(android.widget.ListAdapter)'在null对象引用"

这是words.xml

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


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/action_words"
        android:gravity="center"
        android:textSize="@dimen/abc_text_size_large_material"
        android:layout_marginTop="70dp"
        android:layout_marginLeft="70dp"
        android:layout_marginRight="70dp"
        android:id="@+id/words_textview"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/words_textview"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="60dp"
        android:layout_marginStart="50dp"
        android:layout_marginLeft="50dp"
        android:layout_marginEnd="50dp"
        android:layout_marginRight="50dp">

        <GridView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/gridview"
            android:numColumns="auto_fit"
            android:verticalSpacing="80dp"
            android:horizontalSpacing="40dp"
            android:columnWidth="100dp"
            android:stretchMode="columnWidth"
            android:gravity="center" />


    </LinearLayout>

</RelativeLayout>

这是主要活动java代码

package com.gadgetcatch.firstwords;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

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

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {
                Toast.makeText(MainActivity.this, "" + position,
                        Toast.LENGTH_SHORT).show();
            }
        });

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        /*
      The {@link android.support.v4.view.PagerAdapter} that will provide
      fragments for each of the sections. We use a
      {@link FragmentPagerAdapter} derivative, which will keep every
      loaded fragment in memory. If this becomes too memory intensive, it
      may be best to switch to a
      {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
        SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        /*
      The {@link ViewPager} that will host the section contents.
     */
        ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        //Add a tab bar navigation
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabbar);
        tabLayout.setupWithViewPager(mViewPager);

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setIcon(R.mipmap.ic_launcher);


    }

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c){
            mContext = c;
        }

        public int getCount(){
            return imageIDs.length;
        }

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

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

        private Integer[] imageIDs = {
                R.drawable.animals_png, R.drawable.food_png, R.drawable.clothing_png,
                R.drawable.colors_png, R.drawable.body_png, R.drawable.transport_png
        };

        public View getView(int position, View convertView, ViewGroup parent){
            ImageView imageView;
            if (convertView == null){
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85,85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8,8,8,8);
            }
            else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }




    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            switch (position) {
                case 0:
                    return PlaceholderFragment.newInstance(position + 1);
                case 1:
                    return Words.newInstance(position + 1);
                case 2:
                    return Games.newInstance(position + 1);
            }
            return null;

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }
}

请解释我做错了什么。我还附上了一个应用程序屏幕,可能会帮助您了解我想要做的帽子。在此先感谢您的支持。

Sreen with the App

这也是我在Words.java中的内容:

    public class Words extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public static Words newInstance(int sectionNumber) {
        Words fragment = new Words();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.words,container,false);
        return v;


    }

}

这里是我在Words.java中添加了GridView代码后的内容:

 public class Words extends Fragment {

    GridView gridview;
    private static final String ARG_SECTION_NUMBER = "section_number";

    public static Words newInstance(int sectionNumber) {
        Words fragment = new Words();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.words,container,false);
        GridView gridview = (GridView)v.findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                                    int position, long id) {
                Toast.makeText(MainActivity.this, "" + position,
                        Toast.LENGTH_SHORT).show();
            }
        });

        return v;


    }

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c){
            mContext = c;
        }

        public int getCount(){
            return imageIDs.length;
        }

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

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

        private Integer[] imageIDs = {
                R.drawable.animals_png, R.drawable.food_png, R.drawable.clothing_png,
                R.drawable.colors_png, R.drawable.body_png, R.drawable.transport_png
        };

        public View getView(int position, View convertView, ViewGroup parent){
            ImageView imageView;
            if (convertView == null){
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(85,85));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8,8,8,8);
            }
            else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }

    }
}

现在出现的错误出现在onCreateView上,在gridview.setAdapter上给出了一个错误(new ImageAdapter(this)); (错误是针对&#34;这个&#34;说Image Adapter(android.content.Context)不能应用于com.gadgetcatch.firstwords.Words)

第二个错误是Toast消息说无法解析方法makeText(com.gadgetcatch.firstwords.Words,java.lang.String,int)

0 个答案:

没有答案
相关问题