java - 如何在Android中的GridView中在fragment中显示ArrayList对象

标签 java android gridview android-fragments

我正在尝试学习如何在 fragment 中显示具有 3 列的 GridView 。这些值来自 strings.xml 文件,以数组列表形式提供。当我运行应用程序时它崩溃了。谁能帮我显示 3 列中的值,即地点、描述和时间。我无法继续了解如何在 GridView 中显示读取的值。

My Code are as follows:
**Strings.XML**
    <string-array name="PlacesName">
        <item>Durban</item>
        <item>Paris</item>
        <item>HongKong</item>
        <item>Canada</item>
    </string-array>

    <string-array name="Description">
        <item>Description1</item>
        <item>Description2</item>
        <item>Description3</item>
    </string-array>

    <string-array name="ScheduleDate">
        <item>12/1/2015</item>
        <item>13/2/2015</item>
        <item>14/4/2015</item>
        <item>15/5/2015</item>
    </string-array>

**Fragment**

    */
public class FlightFragment extends Fragment {

    GridView grid;

    public FlightFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_flight, container, false);
        // Inflate the layout for this fragment
        grid = (GridView) view.findViewById(R.id.gridView);
        MyAdapter myAdapter = new MyAdapter();
        grid.setAdapter(myAdapter);
        return view;

    }

    class MyAdapter extends BaseAdapter {

        ArrayList<Schedule> list;
        private Context context;

        MyAdapter() {
            list = new ArrayList();
            Resources resources = context.getResources();
            String[] tempPlaces = resources.getStringArray(R.array.PlacesName);
            String[] tempDate = resources.getStringArray(R.array.ScheduleDate);
            String[] tempDescription = resources.getStringArray(R.array.Description);
            for(int count=0;count<4;count++ ){
                Schedule tempSchedule = new Schedule(tempPlaces[count],tempDate[count],tempDescription[count]);
                list.add(tempSchedule);
            }
        }
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Schedule tempSchedule = list.get(position);
            TextView textView;
            if (convertView == null){
                textView = new TextView(context);
                textView.setLayoutParams(new GridView.LayoutParams(85, 85));
                textView.setPadding(8, 8, 8, 8);
            }
            else{
                textView = (TextView) convertView;
            }
            textView.setText(tempSchedule.Place);
            return textView;
        }
    }

    class Schedule {
        String Place;
        String ScheduleTime;
        String Description;

        Schedule(String place, String scheduleTime, String description ) {
            this.Description = description;
            this.Place = place;
            this.ScheduleTime = scheduleTime;
        }
    }
}

错误

FATAL EXCEPTION: main java.lang.NullPointerException at com.ts.FlightFragment$MyAdapter.(FlightFragment.java:51) at com.ts.FlightFragment.onCreateView(FlightFragment.java:38) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454) at android.os.Handler.handleCallback(Handler.java:725) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5279) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) at dalvik.system.NativeStart.main(Native Method)

最佳答案

问题是您忘记在适配器中分配上下文。您可以通过构造函数传递它。在 Activity 中,您可以简单地使用 this 作为上下文。在您的情况下,在 fragment 中,需要将 getActivity() 作为上下文传递。

public class FlightFragment extends Fragment {

GridView grid;

public FlightFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_flight, container, false);
    // Inflate the layout for this fragment
    grid = (GridView) view.findViewById(R.id.gridView);
    MyAdapter myAdapter = new MyAdapter(getActivity());
    grid.setAdapter(myAdapter);
    return view;

}

class MyAdapter extends BaseAdapter {

    ArrayList<Schedule> list;
    private Context context;

    MyAdapter(Context context) {
        this.context = context;
        list = new ArrayList();
        Resources resources = context.getResources();
        String[] tempPlaces = resources.getStringArray(R.array.PlacesName);
        String[] tempDate = resources.getStringArray(R.array.ScheduleDate);
        String[] tempDescription = resources.getStringArray(R.array.Description);
        for(int count=0;count<4;count++ ){
            Schedule tempSchedule = new Schedule(tempPlaces[count],tempDate[count],tempDescription[count]);
            list.add(tempSchedule);
        }
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Schedule tempSchedule = list.get(position);
        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.grid_row, parent, false);
        }
        TextView placeName = (TextView) convertView.findViewById(R.id.place_name);
        TextView scheduleDate = (TextView) convertView.findViewById(R.id.schedule_date);
        TextView description = (TextView) convertView.findViewById(R.id.description);
        placeName.setText(tempSchedule.Place);
        scheduleDate.setText(tempSchedule.ScheduleTime);
        description.setText(tempSchedule.Description);
        return convertView;
    }
}

在 grid_row.xml 中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical">
    <TextView
        android:id="@+id/place_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/schedule_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

编辑 您需要创建包含 3 个 TextView 的 grid_row.xml。在 getView 上膨胀该布局,然后返回它。 您可以通过使用 ViewHolder Pattern 来提高性能以避免 findViewById() .

关于java - 如何在Android中的GridView中在fragment中显示ArrayList对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28980792/

相关文章:

java - 在 Java 中复制数组

java - 基于 JBoss Form 的自动身份验证

java - 使用 Retrofit Rest Adapter 时出错 : NoClassDefFoundError: Retrofit. Restadapter$Builder

android - 任务 ':app:transformDexWithInstantRunSlicesApkForDebug'的执行失败

java - 添加Spring AOP后@Autowired返回null

java - 减少 Solaris (UNIX) 上多个 Java 进程的内存占用

android - EditText 光标在 Android 5.0 (Lollipop) 上不可见

php - CGridView 中另一个模型的 CButtonColumn

gridview - Specflow - 测试网格数据的正确方法

php - 防止 GridView ActionColumn 图标全局换行