簡體   English   中英

使用適配器將數據從第一個活動傳遞到片段

[英]Pass data from 1st Activity to Fragments using Adapter

我能夠將數據從第一個活動傳遞到第二個活動,但我決定在我的第二個活動中添加片段,現在它不起作用。 我對 Android Studio 完全陌生,我試圖尋找解決方案,但找不到。

我在 logcat 中遇到錯誤

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.galila/com.example.galila.MainDetails}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

這是我的主要活動(第一個活動)

RecyclerView mainRecycler, mpRecycler;
MainAdapter mainAdapter;
MpAdapter mpAdapter;
EditText searchView;
CharSequence search="";

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

    searchView = findViewById(R.id.search);

    mainRecycler = findViewById(R.id.main_recycler);
    mpRecycler = findViewById(R.id.mp_recycler);
    mainRecycler();
    mpRecycler();
}

private void mainRecycler() {
    mainRecycler.setHasFixedSize(true);
    mainRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

    final ArrayList<MainHelperClass> mainLocations = new ArrayList<>();
    mainLocations.add(new MainHelperClass(R.drawable.tondolbeach, R.drawable.tondol_beach1, R.drawable.tondol_beach2, R.drawable.tondol_beach3, R.drawable.tondol_beach4, "Tondol Beach", "Anda, Pangasinan", "Tondol Beach is located at the northern tip of Anda, an island municipality that used to be accessible only by boat across the narrow Catubig Channel. What makes Tondol unique is its long, shallow nature. There is a considerable amount of marine life besides starfish and crabs on the shallow beach.", "Manila - Tondol Beach", "5 hrs 19 mins (291.1 km)", "Swimming", "Sightseeing", "Boat Ride", "Eat Seafoods", "Party"));
    mainLocations.add(new MainHelperClass(R.drawable.saintspeterandpaul, R.drawable.calasiao_church1, R.drawable.calasiao_church2, R.drawable.calasiao_church3, R.drawable.calasiao_church4, "Calasiao Church", "Calasiao, Pangasinan", "The Saints Peter and Paul Parish Church (Iglesia Parroquial de los Pedro y Pablo), commonly know as Calasiao Church is a baroque church located in Poblacion West, Calasiao, Pangasinan, Philippines. It was founded in 1588 by the Spaniards. It is 88.3 meter long, 25 meters wide and 27.3 meters high. It was declared as a National Treasure in 2001.", "Manila - Calasiao", "3 hrs 26 mins (211.6 km)", "Attend Mass", "Souvenirs", "Local Foods", "Sightseeing", "Fiesta"));
    mainLocations.add(new MainHelperClass(R.drawable.manaoagchurch, R.drawable.manaoag_church1, R.drawable.manaoag_church2, R.drawable.manaoag_church3, R.drawable.manaoag_church4, "Manaoag Church", "Manaoag, Pangasinan", "Our Lady of Manaoag is a top-rated destination in the Philippines for Catholic travelers around the world. 'Our Lady of the Most Holy Rosary of Manaoag' or known as 'Our Lady of Manaoag' is one of the most visited church in Pangasinan. It was built in the 17th century. Thousands of people come to the province every year to experience the spiritual nature of the area and take in different historical and religious attractions.", "Manila - Manaoag Church", "3 hrs 3 mins (198.9 km)", "Attend Mass", "Souvenirs", "Local Foods", "Sightseeing", "Fiesta"));
    mainLocations.add(new MainHelperClass(R.drawable.patarbeach, R.drawable.patar_beach1, R.drawable.patar_beach2, R.drawable.patar_beach3, R.drawable.patar_beach4, "Patar Beach", "Bolinao, Pangasinan", "Bolinao is known for a number of prestine beaches, the most popular one is the Patar Beach which dubbed as the Boracay of the North, located on the western coast along the South China Sea southwest of the town proper. Patar Beach is a creamy white sand beach that slopes gradually from shore making it good for swimming.", "Manila - Patar Beach", "5 hrs 25 mins (298.4 km)", "Swimming", "Sightseeing", "Boat Ride", "Eat Seafoods", "Party"));
    mainLocations.add(new MainHelperClass(R.drawable.hundredisland, R.drawable.hundred_island_gallery1, R.drawable.hundred_island_gallery2, R.drawable.hundred_island_gallery3, R.drawable.hundred_island_gallery4, "Hundred Islands", "Alaminos, Pangasinan", "The Hundred Islands National Park is the first national park and a protected area located in Alaminos, Pangasinan in the Northern Philippines. The islands, totaling 124 at low tide and 123 at high tide, are scattered in Lingayen Gulf covering an area of 16.76 square kilometers (6.47 sq mi.). Only three of them have been developed for tourism: Governor Island, Quezon Island and Childrens Island.", "Manila - Hundred Islands", "3 hrs 10 mins (205 km)", "Swimming", "Island Hoping", "Snorkeling", "Kayaking", "Zipline"));
    mainLocations.add(new MainHelperClass(R.drawable.bolinao_lighthouse, R.drawable.bolinao_lighthouse_1, R.drawable.bolinao_lighthouse_2, R.drawable.bolinao_lighthouse_3, R.drawable.bolinao_lighthouse_4, "Bolinao Lighthouse", "Bolinao, Pangasinan", "The Cape of Bolinao Lighthouse at Patar rises 351 ft (107 m) above sea level atop Punta Piedra Point, a towering hill of solid rock which is the sharp point of Cape Bolinao itself. It was built by the Americans in 1903. The lighthouse provides a panoramic view of a portion of the 1269 hectares Cape Bolinao Dendro Thermal Ipil-Ipil Plantation on a land area where archeological excavations have revealed relics from 14th to 15th centuries.", "Manila - Bolinao Lighthouse", "5 hrs 20 mins (284.1 km)", "Sightseeing", "Exploration", "Local Foods", "Photoshoot", "Souvenirs"));
    mainLocations.add(new MainHelperClass(R.drawable.st_james_the_great, R.drawable.st_james_the_great_1, R.drawable.st_james_the_great_2, R.drawable.st_james_the_great_3, R.drawable.st_james_the_great_4, "St. James the Great Church", "Bolinao, Pangasinan", "The Saint James the Great Parish Church is a Spanish colonial church located at Brgy. Germinal in Bolinao, Pangasinan. The church was made out of black coral stones. It is one of the oldest church in Pangasinan, it was constructed in 1600s and survived multiple natural and manmade calamities like 1788 earthquake, 1819 fire and 2009 typhoon.", "Manila - St. James the Great Church", "5 hrs 6 mins (286 km)", "Attend Mass", "Souvenirs", "Local Foods", "Sightseeing", "Fiesta"));
    mainLocations.add(new MainHelperClass(R.drawable.bolinao_falls, R.drawable.bolinao_falls_1, R.drawable.bolinao_falls_2, R.drawable.bolinao_falls_3, R.drawable.bolinao_falls_4, "Bolinao Falls", "Bolinao, Pangasinan", "Bolinao Falls is a short waterfall which is a result varying elevations of the Balingasay River, thus the water falls down to a pool of water located on a lower elevation. Bolinao Falls is about 19 kilometers away from Bolinao town proper. Its divided into three waterfalls, all located along the Bolinao river. Each falls has different views and features.", "Manila - Bolinao Falls", "5 hrs 3 mins (277.3 km)", "Cliff Diving", "Swimming", "Sightseeing", "Exploration", "Photoshoot"));
    mainLocations.add(new MainHelperClass(R.drawable.enchanted_cave, R.drawable.enchanted_cave_1, R.drawable.enchanted_cave_2, R.drawable.enchanted_cave_3, R.drawable.enchanted_cave_4, "Enchanted Cave", "Bolinao, Pangasinan", "Enchanted Cave is one of the must visit attractions in Bolinao, Pangasinan. The name itself portrays its mystical beauty. The entire place is really enchanted since it is like a huge coral reef that emerged underwater. The water inside the cave is clear and not salty. Its depth is estimated around 3-6 ft. Enchanted Cave offers underground pool with crystal clear spring water, natural sea rock hill terrain, and etc.", "Manila - Enchanted Cave", "5 hrs 26 mins (297.6 km)", "Swimming", "Sightseeing", "Exploration", "Photoshoot", "Local Foods"));
    mainLocations.add(new MainHelperClass(R.drawable.tondaligan_beach, R.drawable.tondaligan_beach_1, R.drawable.tondaligan_beach_2, R.drawable.tondaligan_beach_3, R.drawable.tondaligan_beach_4, "Tondaligan Beach", "Dagupan, Pangasinan", "One of the most visited beach in Dagupan. Its fine sands and numerous coconut trees attract people all year-round, the beach area is quite large so no need to worry about running out of good spots.", "Manila - Tondaligan Beach", "3 hrs 30 mins (219.2 km)", "Swimming", "Boat Ride", "Sightseeing", "Eat Seafoods", "Party"));

    mainAdapter = new MainAdapter(mainLocations, getApplicationContext());
    mainRecycler.setAdapter(mainAdapter);

    searchView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            mainAdapter.getFilter().filter(charSequence);
            search = charSequence;
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

}

private void mpRecycler() {
    mpRecycler.setHasFixedSize(true);
    mpRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

    ArrayList<MpHelperClass> mpLocations = new ArrayList<>();
    mpLocations.add(new MpHelperClass(R.drawable.hundredisland, R.drawable.hundred_island_gallery1, R.drawable.hundred_island_gallery2, R.drawable.hundred_island_gallery3, R.drawable.hundred_island_gallery4, "Hundred Islands", "Alaminos, Pangasinan", "The Hundred Islands National Park is the first national park and a protected area located in Alaminos, Pangasinan in the Northern Philippines. The islands, totaling 124 at low tide and 123 at high tide, are scattered in Lingayen Gulf covering an area of 16.76 square kilometers (6.47 sq mi.). Only three of them have been developed for tourism: Governor Island, Quezon Island and Childrens Island.", "Ratings: 4.5", "Manila - Hundred Islands", "3 hrs 10 mins (205 km)", "Swimming", "Island Hoping", "Snorkeling", "Kayaking", "Zipline"));
    mpLocations.add(new MpHelperClass(R.drawable.patarbeach, R.drawable.patar_beach1, R.drawable.patar_beach2, R.drawable.patar_beach3, R.drawable.patar_beach4, "Patar Beach", "Bolinao, Pangasinan", "Bolinao is known for a number of prestine beaches, the most popular one is the Patar Beach which dubbed as the Boracay of the North, located on the western coast along the South China Sea southwest of the town proper. Patar Beach is a creamy white sand beach that slopes gradually from shore making it good for swimming.", "Ratings: 4.5", "Manila - Patar Beach", "5 hrs 25 mins (298.4 km)", "Swimming", "Sightseeing", "Boat Ride", "Eat Seafoods", "Party"));
    mpLocations.add(new MpHelperClass(R.drawable.bolinao_falls, R.drawable.bolinao_falls_1, R.drawable.bolinao_falls_2, R.drawable.bolinao_falls_3, R.drawable.bolinao_falls_4, "Bolinao Falls", "Bolinao, Pangasinan", "Bolinao Falls is a short waterfall which is a result varying elevations of the Balingasay River, thus the water falls down to a pool of water located on a lower elevation. Bolinao Falls is about 19 kilometers away from Bolinao town proper. Its divided into three waterfalls, all located along the Bolinao river. Each falls has different views and features.", "Ratings: 4.5", "Manila - Bolinao Falls", "5 hrs 3 mins (277.3 km)", "Cliff Diving", "Swimming", "Sightseeing", "Exploration", "Photoshoot"));
    mpLocations.add(new MpHelperClass(R.drawable.tondolbeach, R.drawable.tondol_beach1, R.drawable.tondol_beach2, R.drawable.tondol_beach3, R.drawable.tondol_beach4, "Tondol Beach", "Anda, Pangasinan", "Tondol Beach is located at the northern tip of Anda, an island municipality that used to be accessible only by boat across the narrow Catubig Channel. What makes Tondol unique is its long, shallow nature. There is a considerable amount of marine life besides starfish and crabs on the shallow beach.", "Ratings: 4", "Manila - Tondol Beach", "5 hrs 19 mins (291.1 km)", "Swimming", "Sightseeing", "Boat Ride", "Eat Seafoods", "Party"));
    mpLocations.add(new MpHelperClass(R.drawable.manaoagchurch, R.drawable.manaoag_church1, R.drawable.manaoag_church2, R.drawable.manaoag_church3, R.drawable.manaoag_church4, "Manaoag Church", "Manaoag, Pangasinan", "Our Lady of Manaoag is a top-rated destination in the Philippines for Catholic travelers around the world. 'Our Lady of the Most Holy Rosary of Manaoag' or known as 'Our Lady of Manaoag' is one of the most visited church in Pangasinan. It was built in the 17th century. Thousands of people come to the province every year to experience the spiritual nature of the area and take in different historical and religious attractions.", "Ratings: 4", "Manila - Manaoag Church", "3 hrs 3 mins (198.9 km)", "Attend Mass", "Souvenirs", "Local Foods", "Sightseeing", "Fiesta"));
    mpLocations.add(new MpHelperClass(R.drawable.st_james_the_great, R.drawable.st_james_the_great_1, R.drawable.st_james_the_great_2, R.drawable.st_james_the_great_3, R.drawable.st_james_the_great_4, "St. James the Great Church", "Bolinao, Pangasinan", "The Saint James the Great Parish Church is a Spanish colonial church located at Brgy. Germinal in Bolinao, Pangasinan. The church was made out of black coral stones. It is one of the oldest church in Pangasinan, it was constructed in 1600s and survived multiple natural and manmade calamities like 1788 earthquake, 1819 fire and 2009 typhoon.", "Ratings: 4", "Manila - St. James the Great Church", "5 hrs 6 mins (286 km)", "Attend Mass", "Souvenirs", "Local Foods", "Sightseeing", "Fiesta"));
    mpLocations.add(new MpHelperClass(R.drawable.enchanted_cave, R.drawable.enchanted_cave_1, R.drawable.enchanted_cave_2, R.drawable.enchanted_cave_3, R.drawable.enchanted_cave_4, "Enchanted Cave", "Bolinao, Pangasinan", "Enchanted Cave is one of the must visit attractions in Bolinao, Pangasinan. The name itself portrays its mystical beauty. The entire place is really enchanted since it is like a huge coral reef that emerged underwater. The water inside the cave is clear and not salty. Its depth is estimated around 3-6 ft. Enchanted Cave offers underground pool with crystal clear spring water, natural sea rock hill terrain, and etc.", "Ratings: 4", "Manila - Enchanted Cave", "5 hrs 26 mins (297.6 km)", "Swimming", "Sightseeing", "Exploration", "Photoshoot", "Local Foods"));
    mpLocations.add(new MpHelperClass(R.drawable.bolinao_lighthouse, R.drawable.bolinao_lighthouse_1, R.drawable.bolinao_lighthouse_2, R.drawable.bolinao_lighthouse_3, R.drawable.bolinao_lighthouse_4, "Bolinao Lighthouse", "Bolinao, Pangasinan", "The Cape of Bolinao Lighthouse at Patar rises 351 ft (107 m) above sea level atop Punta Piedra Point, a towering hill of solid rock which is the sharp point of Cape Bolinao itself. It was built by the Americans in 1903. The lighthouse provides a panoramic view of a portion of the 1269 hectares Cape Bolinao Dendro Thermal Ipil-Ipil Plantation on a land area where archeological excavations have revealed relics from 14th to 15th centuries.", "Ratings: 4", "Manila - Bolinao Lighthouse", "5 hrs 20 mins (284.1 km)", "Sightseeing", "Exploration", "Local Foods", "Photoshoot", "Souvenirs"));
    mpLocations.add(new MpHelperClass(R.drawable.tondaligan_beach, R.drawable.tondaligan_beach_1, R.drawable.tondaligan_beach_2, R.drawable.tondaligan_beach_3, R.drawable.tondaligan_beach_4, "Tondaligan Beach", "Dagupan, Pangasinan", "One of the most visited beach in Dagupan. Its fine sands and numerous coconut trees attract people all year-round, the beach area is quite large so no need to worry about running out of good spots.", "Ratings: 3.5", "Manila - Tondaligan Beach", "3 hrs 30 mins (219.2 km)", "Swimming", "Boat Ride", "Sightseeing", "Eat Seafoods", "Party"));
    mpLocations.add(new MpHelperClass(R.drawable.saintspeterandpaul, R.drawable.calasiao_church1, R.drawable.calasiao_church2, R.drawable.calasiao_church3, R.drawable.calasiao_church4, "Calasiao Church", "Calasiao, Pangasinan", "The Saints Peter and Paul Parish Church (Iglesia Parroquial de los Pedro y Pablo), commonly know as Calasiao Church is a baroque church located in Poblacion West, Calasiao, Pangasinan, Philippines. It was founded in 1588 by the Spaniards. It is 88.3 meter long, 25 meters wide and 27.3 meters high. It was declared as a National Treasure in 2001.", "Ratings: 3.5", "Manila - Calasiao", "3 hrs 26 mins (211.6 km)", "Attend Mass", "Souvenirs", "Local Foods", "Sightseeing", "Fiesta"));

    mpAdapter = new MpAdapter(mpLocations, getApplicationContext());
    mpRecycler.setAdapter(mpAdapter);
}

}

這是我的適配器類

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> implements Filterable {

ArrayList<MainHelperClass> mainLocations;
ArrayList<MainHelperClass> filteredMainLocations;
Context context;
public MainAdapter(ArrayList<MainHelperClass> mainLocations, Context context) {
    this.mainLocations = mainLocations;
    this.context = context;
    this.filteredMainLocations = mainLocations;
}


@NonNull
@Override
public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_card_design,parent,false);
    MainViewHolder mainViewHolder = new MainViewHolder(view);
    return mainViewHolder;
}

@Override
public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {

    final MainHelperClass mainHelperClass = filteredMainLocations.get(position);
    holder.image.setImageResource(mainHelperClass.getImage());
    holder.gallery1.setImageResource(mainHelperClass.getGallery1());
    holder.gallery2.setImageResource(mainHelperClass.getGallery2());
    holder.gallery3.setImageResource(mainHelperClass.getGallery3());
    holder.gallery4.setImageResource(mainHelperClass.getGallery4());
    holder.placeName.setText(mainHelperClass.getPlaceName());
    holder.location.setText(mainHelperClass.getLocation());
    holder.description.setText(mainHelperClass.getDescription());
    holder.distance.setText(mainHelperClass.getDistance());
    holder.km.setText(mainHelperClass.getKm());
    holder.todo1.setText(mainHelperClass.getTodo1());
    holder.todo2.setText(mainHelperClass.getTodo2());
    holder.todo3.setText(mainHelperClass.getTodo3());
    holder.todo4.setText(mainHelperClass.getTodo4());
    holder.todo5.setText(mainHelperClass.getTodo5());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, MainDetails.class);
            intent.putExtra("image", mainHelperClass.getImage());
            intent.putExtra("gallery1", mainHelperClass.getGallery1());
            intent.putExtra("gallery2", mainHelperClass.getGallery2());
            intent.putExtra("gallery3", mainHelperClass.getGallery3());
            intent.putExtra("gallery4", mainHelperClass.getGallery4());
            intent.putExtra("place name", mainHelperClass.getPlaceName());
            intent.putExtra("location", mainHelperClass.getLocation());
            intent.putExtra("description", mainHelperClass.getDescription());
            intent.putExtra("distance", mainHelperClass.getDistance());
            intent.putExtra("km", mainHelperClass.getKm());
            intent.putExtra("todo1", mainHelperClass.getTodo1());
            intent.putExtra("todo2", mainHelperClass.getTodo2());
            intent.putExtra("todo3", mainHelperClass.getTodo3());
            intent.putExtra("todo4", mainHelperClass.getTodo4());
            intent.putExtra("todo5", mainHelperClass.getTodo5());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return filteredMainLocations.size();
}

public static class MainViewHolder extends RecyclerView.ViewHolder{

    ImageView image, gallery1, gallery2, gallery3, gallery4;
    TextView placeName, location, description, distance, km, todo1, todo2, todo3, todo4, todo5;

    public MainViewHolder(@NonNull View itemView) {
        super(itemView);
        image = itemView.findViewById(R.id.main_image);
        gallery1 = itemView.findViewById(R.id.main_gallery_1);
        gallery2 = itemView.findViewById(R.id.main_gallery_2);
        gallery3 = itemView.findViewById(R.id.main_gallery_3);
        gallery4 = itemView.findViewById(R.id.main_gallery_4);
        placeName = itemView.findViewById(R.id.main_place_name);
        location = itemView.findViewById(R.id.main_location);
        description = itemView.findViewById(R.id.main_description);
        distance = itemView.findViewById(R.id.main_distance);
        km = itemView.findViewById(R.id.main_km);
        todo1 = itemView.findViewById(R.id.main_todo1);
        todo2 = itemView.findViewById(R.id.main_todo2);
        todo3 = itemView.findViewById(R.id.main_todo3);
        todo4 = itemView.findViewById(R.id.main_todo4);
        todo5 = itemView.findViewById(R.id.main_todo5);
    }
}

   public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {

            String key = charSequence.toString();
            if (key.isEmpty()) {
                filteredMainLocations = mainLocations;
            }else {
                ArrayList<MainHelperClass> isFiltered = new ArrayList<>();
                for (MainHelperClass row : mainLocations) {
                    if (row.getPlaceName().toLowerCase().contains(key.toLowerCase())) {
                        isFiltered.add(row);
                    }

                    else if (row.getLocation().toLowerCase().contains(key.toLowerCase())) {
                        isFiltered.add(row);
                    }
                }

                filteredMainLocations = isFiltered;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = filteredMainLocations;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults filterResults) {
            filteredMainLocations = (ArrayList<MainHelperClass>) filterResults.values;
            notifyDataSetChanged();
        }
    };
  }
}

這是我的 DetailsActivity(第二個 Activity),我想在這里創建 Fragments 用於導航目的

public class MainDetails extends AppCompatActivity {
ImageView image, gallery1, gallery2, gallery3, gallery4;
TextView placeName, location, description, distance, km, todo1, todo2, todo3, todo4, todo5;
Button descriptionFragment, distanceFragment, galleryFragment, todoFragment;

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

    descriptionFragment = (Button) findViewById(R.id.description_fragment);
    distanceFragment = (Button)findViewById(R.id.distance_fragment);
    galleryFragment = (Button)findViewById(R.id.gallery_fragment);
    todoFragment = (Button)findViewById(R.id.todo_fragment);

    descriptionFragment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setFragment(new DescriptionFragment());
        }
    });

    distanceFragment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setFragment(new DistanceFragment());
        }
    });

    galleryFragment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setFragment(new GalleryFragment());
        }
    });

    todoFragment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setFragment(new TodoFragment());
        }
    });

    image = (ImageView)findViewById(R.id.main_image_details);
    gallery1 = (ImageView)findViewById(R.id.main_gallery_details_1);
    gallery2 = (ImageView)findViewById(R.id.main_gallery_details_2);
    gallery3 = (ImageView)findViewById(R.id.main_gallery_details_3);
    gallery4 = (ImageView)findViewById(R.id.main_gallery_details_4);
    placeName = (TextView)findViewById(R.id.main_place_name_details);
    location = (TextView)findViewById(R.id.main_loc_details);
    description = (TextView)findViewById(R.id.main_desc_details);
    distance = (TextView)findViewById(R.id.main_distance_details);
    km = (TextView)findViewById(R.id.main_km_details);
    todo1 = (TextView)findViewById(R.id.main_todo1_details);
    todo2 = (TextView)findViewById(R.id.main_todo2_details);
    todo3 = (TextView)findViewById(R.id.main_todo3_details);
    todo4 = (TextView)findViewById(R.id.main_todo4_details);
    todo5 = (TextView)findViewById(R.id.main_todo5_details);

    image.setImageResource(getIntent().getIntExtra("image", 0));
    gallery1.setImageResource(getIntent().getIntExtra("gallery1", 0));
    gallery2.setImageResource(getIntent().getIntExtra("gallery2", 0));
    gallery3.setImageResource(getIntent().getIntExtra("gallery3", 0));
    gallery4.setImageResource(getIntent().getIntExtra("gallery4", 0));
    placeName.setText(getIntent().getStringExtra("place name"));
    location.setText(getIntent().getStringExtra("location"));
    description.setText(getIntent().getStringExtra("description"));
    distance.setText(getIntent().getStringExtra("distance"));
    km.setText(getIntent().getStringExtra("km"));
    todo1.setText(getIntent().getStringExtra("todo1"));
    todo2.setText(getIntent().getStringExtra("todo2"));
    todo3.setText(getIntent().getStringExtra("todo3"));
    todo4.setText(getIntent().getStringExtra("todo4"));
    todo5.setText(getIntent().getStringExtra("todo5"));

    final ImageView image1 = (ImageView) findViewById(R.id.main_image_details);
    final ImageView gallery1 = (ImageView) findViewById(R.id.main_gallery_details_1);
    gallery1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            image1.setImageResource(getIntent().getIntExtra("gallery1", 0));
        }
    });

    final ImageView image2 = (ImageView) findViewById(R.id.main_image_details);
    final ImageView gallery2 = (ImageView) findViewById(R.id.main_gallery_details_2);
    gallery2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            image2.setImageResource(getIntent().getIntExtra("gallery2", 0));
        }
    });

    final ImageView image3 = (ImageView) findViewById(R.id.main_image_details);
    final ImageView gallery3 = (ImageView) findViewById(R.id.main_gallery_details_3);
    gallery3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            image3.setImageResource(getIntent().getIntExtra("gallery3", 0));
        }
    });

    final ImageView image4 = (ImageView) findViewById(R.id.main_image_details);
    final ImageView gallery4 = (ImageView) findViewById(R.id.main_gallery_details_4);
    gallery4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            image4.setImageResource(getIntent().getIntExtra("gallery4", 0));
        }
    });
}

private void setFragment(Fragment Fragment) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.replace(R.id.flFragment, Fragment);
    fragmentTransaction.commit();

}

}

您需要使用 Bundle 將數據從活動傳遞到片段

這是一個示例代碼:

創建捆綁包 object 並像這樣分配值

 Bundle bundle = new Bundle();
 bundle.putString("image", mainHelperClass.getImage());
 bundle.putString("gallery1", mainHelperClass.getGallery1());
 bundle.putString("gallery2", mainHelperClass.getGallery2());
 bundle.putString("gallery3", mainHelperClass.getGallery3());
 bundle.putString("gallery4", mainHelperClass.getGallery4());
 bundle.putString("place name", mainHelperClass.getPlaceName());
 bundle.putString("location", mainHelperClass.getLocation());
 bundle.putString("description", mainHelperClass.getDescription());
 bundle.putString("distance", mainHelperClass.getDistance());
 bundle.putString("km", mainHelperClass.getKm());
 bundle.putString("todo1", mainHelperClass.getTodo1());
 bundle.putString("todo2", mainHelperClass.getTodo2());
 bundle.putString("todo3", mainHelperClass.getTodo3());
 bundle.putString("todo4", mainHelperClass.getTodo4());
 bundle.putString("todo5", mainHelperClass.getTodo5());

調用片段並從適配器 class 傳遞 arguments

    YourFragment fragment = new YourFragment();
    fragment.setArguments(bundle);
    FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame_id, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

您可以通過Bundle將數據活動傳遞給片段

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

在片段中獲取這些數據

String strtext = getArguments().getString("edttext");    
return inflater.inflate(R.layout.fragment, container, false);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM