Java 如何成功实现viewpager和recyclerView从活动迁移到片段

Java 如何成功实现viewpager和recyclerView从活动迁移到片段,java,android,xml,android-fragments,android-viewpager,Java,Android,Xml,Android Fragments,Android Viewpager,我正在学习udacity android basic nanodegree课程,为了实现recyclerView viewPager,我们被指示将代码从一个活动移动到另一个片段,我已经按照指示进行了操作,但当我运行应用程序时,它甚至在显示第一页之前就崩溃了,我的调试器将我指向一行(第18行)在MainActivity.java文件中,该文件是setContentView(R.layout.activity_main); 我已经完成了所有可以在stack overflow和其他教程中找到的修复,但

我正在学习udacity android basic nanodegree课程,为了实现recyclerView viewPager,我们被指示将代码从一个活动移动到另一个片段,我已经按照指示进行了操作,但当我运行应用程序时,它甚至在显示第一页之前就崩溃了,我的调试器将我指向一行(第18行)在MainActivity.java文件中,该文件是setContentView(R.layout.activity_main); 我已经完成了所有可以在stack overflow和其他教程中找到的修复,但似乎没有任何东西适合我。我不知道还能做什么。帮助摆脱困境请

package com.example.tournaija;

import android.os.Bundle;
import androidx.viewpager.widget.PagerAdapter;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;


public class MainActivity extends AppCompatActivity {

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

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);

        // Find the view pager that will allow the user to swipe between fragments
        ViewPager viewPager = findViewById(R.id.viewpager);

        // Create an adapter that knows which fragment should be shown on each page
        CategoryAdapter adapter = new CategoryAdapter(getSupportFragmentManager());

        // Set the adapter onto the view pager
        viewPager.setAdapter(adapter);
    }
}
这是主要活动的xml布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.tournaija.MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
其中一个活动和对应的xml片段

活动

package com.example.tournaija;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class HotelsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, new HotelsFragment())
                .commit();
    }
}
碎片

package com.example.tournaija;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class HotelsFragment extends Fragment {

    ArrayList<Place> placeArrayList = new ArrayList<>();

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.place_list, container, false);
        placeArrayList.add(new Place("Radisson Blu Anchorage Hotel, Lagos",
                "Situated in the heart of Lagos, Nigeria, Radisson " +
                        "Blu Anchorage Hotel, is a stunning masterpiece styled " +
                        "by famous Swedish hospitality designer, Christian Lundwall. " +
                        "The Radisson Blu Anchorage Hotel, Lagos, Nigeria is nestled " +
                        "along the Lagos Lagoon on Victoria Island in the midst of the " +
                        "business district and banking area. This Lagos hotel has " +
                        "170 air-conditioned rooms, including 8 unique and opulently " +
                        "furnished suites, offering both stunning city and lagoon views. " +
                        "The Voyage buffet-style restaurant serves a range of eclectic, " +
                        "international cuisine and local dishes, while overlooking " +
                        "the Lagos Lagoon. The View bar lounge is ideal for snacks and " +
                        "drinks, and perfect for a Classic Cocktail as the sun sets. " +
                        "Providing jetty access, the Surface Bar and Grill on the terrace " +
                        "offers outdoor dining overlooking the lagoon. Guests enjoy free " +
                        "access to the hotel fitness area, complete with cardiovascular gym, " +
                        "massage room, outdoor infinity swimming pool, and steam room.The hotel " +
                        "boasts two upscale boardrooms and four spacious meeting rooms, all " +
                        "offering natural light as well as all the modern, audiovisual " +
                        "equipment expected of a World Class Hotel. All you need for " +
                        "a successful stay!",
                R.drawable.radisson_blu));

        PlaceAdapter placeAdapter = new PlaceAdapter(getActivity(), placeArrayList);
        ListView placeList = rootView.findViewById(R.id.place_layout);

        // hooking the adapter
        placeList.setAdapter(placeAdapter);

        return rootView;
    }


}
package com.example.tournaija;
导入android.os.Bundle;
导入androidx.fragment.app.fragment;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ListView;
导入android.widget.TextView;
导入java.util.ArrayList;
/**
*一个简单的{@link Fragment}子类。
*/
公共类HotelsFragment扩展了片段{
ArrayList placeArrayList=新的ArrayList();
公共酒店{
//必需的空公共构造函数
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.place\u列表,容器,错误);
placeArrayList.add(新地点(“拉各斯雷迪森蓝光安克雷奇酒店”),
“位于尼日利亚拉各斯市中心,Radisson”+
“布鲁安克雷奇酒店是一个令人惊叹的杰作”+
“由瑞典著名酒店设计师克里斯蒂安·伦德沃尔(Christian Lundwall)设计。”+
尼日利亚拉各斯雷迪森蓝光安克雷奇酒店+
“沿着维多利亚岛上的拉各斯泻湖,在大西洋中部”+
“商业区和银行区。这家拉各斯酒店有”+
170间空调房,包括8间独特而豪华的客房+
“家具齐全的套房,既能欣赏到迷人的城市景色,又能欣赏到泻湖美景。”+
“航程自助式餐厅提供多种多样的服务+
“国际美食和本地菜肴,同时俯瞰”+
“拉各斯泻湖。观景酒吧酒廊是小吃和休闲的理想场所”+
“喝一杯,日落时喝一杯经典鸡尾酒再合适不过了。”+
提供码头通道、露台上的露天酒吧和格栅+
“提供可俯瞰泻湖的户外餐饮。客人可免费享用”+
进入酒店健身区,配备心血管健身房+
按摩室、室外无限游泳池和蒸汽房。酒店+
拥有两间高档会议室和四间宽敞的会议室+
提供自然光和所有现代视听设备+
“世界级酒店所需的设备。您所需的一切”+
“祝您入住愉快!”,
R.drawable.radisson_blu);
PlaceAdapter PlaceAdapter=新的PlaceAdapter(getActivity(),placeArrayList);
ListView placeList=rootView.findViewById(R.id.place\u布局);
//钩住适配器
placeList.setAdapter(placeAdapter);
返回rootView;
}
}
Xml


只需在
MainActivity.onCreate()
中添加一个
片段
。。。否则,这些字段将是
MainActivity
的成员,而不是通常认为的
片段的成员。此外,在XML中使用android.support.v4.view.ViewPager
是没有意义的

package com.example.tournaija;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class HotelsFragment extends Fragment {

    ArrayList<Place> placeArrayList = new ArrayList<>();

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.place_list, container, false);
        placeArrayList.add(new Place("Radisson Blu Anchorage Hotel, Lagos",
                "Situated in the heart of Lagos, Nigeria, Radisson " +
                        "Blu Anchorage Hotel, is a stunning masterpiece styled " +
                        "by famous Swedish hospitality designer, Christian Lundwall. " +
                        "The Radisson Blu Anchorage Hotel, Lagos, Nigeria is nestled " +
                        "along the Lagos Lagoon on Victoria Island in the midst of the " +
                        "business district and banking area. This Lagos hotel has " +
                        "170 air-conditioned rooms, including 8 unique and opulently " +
                        "furnished suites, offering both stunning city and lagoon views. " +
                        "The Voyage buffet-style restaurant serves a range of eclectic, " +
                        "international cuisine and local dishes, while overlooking " +
                        "the Lagos Lagoon. The View bar lounge is ideal for snacks and " +
                        "drinks, and perfect for a Classic Cocktail as the sun sets. " +
                        "Providing jetty access, the Surface Bar and Grill on the terrace " +
                        "offers outdoor dining overlooking the lagoon. Guests enjoy free " +
                        "access to the hotel fitness area, complete with cardiovascular gym, " +
                        "massage room, outdoor infinity swimming pool, and steam room.The hotel " +
                        "boasts two upscale boardrooms and four spacious meeting rooms, all " +
                        "offering natural light as well as all the modern, audiovisual " +
                        "equipment expected of a World Class Hotel. All you need for " +
                        "a successful stay!",
                R.drawable.radisson_blu));

        PlaceAdapter placeAdapter = new PlaceAdapter(getActivity(), placeArrayList);
        ListView placeList = rootView.findViewById(R.id.place_layout);

        // hooking the adapter
        placeList.setAdapter(placeAdapter);

        return rootView;
    }


}
<?xml version="1.0" encoding="utf-8"?>
<ListView 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"
    android:id="@+id/place_layout"/>