如何在 Android Studio 的片段中使用适配器实现列表视图

How to implement a listview with an adapter in a fragment in Android Studio

我是 Android Studio 的新手,我正在尝试使用适配器在片段中实现列表视图。启动我的应用程序后,我收到此错误消息

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

这似乎与我的适配器有关。这是我的代码:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, 123);
        } else {
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();

        bottomNav.setSelectedItemId(R.id.nav_home);

        bottomNav.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment fragment = null;

                switch (item.getItemId()){

                   case R.id.nav_home:
                       fragment = new HomeFragment();
                        break;
                    case R.id.nav_profil:
                        fragment = new ProfilFragment();
                        break;
                   case R.id.nav_camera:
                      fragment = new CameraFragment();
                        break;

                }

                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
                return true;
        }

   });

}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom_navigation"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bttom_navigation"
        app:itemIconTint="@color/white"
        android:background="@android:color/holo_blue_dark"/>

</RelativeLayout>

HomeFragment.java

public class HomeFragment extends Fragment {

    String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
    String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
    int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);

        ListView listView = (ListView) getActivity().findViewById(R.id.Listview);
        MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
        listView.setAdapter(myadapter);

        // Inflate the layout for this fragment
        return view;
    }

}

fragment_home.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">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Listview"
        >

    </ListView>
</LinearLayout>

MyAdapter.java

public class MyAdapter extends BaseAdapter {

    Context context;
    String listFilm[];
    String lieuFilm[];
    int listImages[];
    LayoutInflater inflater;

    public MyAdapter(Context ctx, String[] nomFilm, String[] desFilm, int[] images ){

        this.context = ctx;
        this.listFilm = nomFilm;
        this.lieuFilm = desFilm;
        this.listImages = images;
        inflater = LayoutInflater.from(ctx);


    }

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

    @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 = inflater.inflate(R.layout.row, null);
        TextView txtview = (TextView) convertView.findViewById(R.id.textView1);
        TextView txtview2 = (TextView)  convertView.findViewById(R.id.textView2);
        ImageView imgview = (ImageView) convertView.findViewById(R.id.image);

        txtview.setText(listFilm[position]);
        txtview2.setText(lieuFilm[position]);
        imgview.setImageResource(listImages[position]);
        return convertView;
    }
}

row.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="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <ImageView
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/image"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Main Title"
        android:textColor="#000"
        android:layout_margin="5dp"
        android:textSize="20sp"
        android:id="@+id/textView1"
        />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Sub Title"
            android:textColor="#a9a9a9"
            android:layout_margin="5dp"
            android:textSize="15sp"
            android:id="@+id/textView2"
            />

    </LinearLayout>

</LinearLayout>

错误指向我的HomeFragment的第32行,这是我的listView.setAdapter(myadapter);

不,你的适配器没有问题,但你的列表视图有问题。

HomeFragment.java

    public class HomeFragment extends Fragment {
    
        String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
        String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
        int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_home, container, false);
    

...

            ListView listView = (ListView) view.findViewById(R.id.Listview); //use listview from inflater view instead of getActivity
          
...

  MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
            listView.setAdapter(myadapter);
    
            // Inflate the layout for this fragment
            return view;
        }
    
    }

public class HomeFragment 扩展片段 {

String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_home, container, false);

    ListView listView = (ListView) getActivity().findViewById(R.id.Listview);
    MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
    listView.setAdapter(myadapter);

    // Inflate the layout for this fragment
    return view;
}

}

你必须使用 :=

ListView listView = (ListView) view.findViewById(R.id.Listview);

代替此代码:=

ListView listView = (ListView) getActivity().findViewById(R.id.Listview);