使用set方法将数据从活动发送到片段

时间:2016-04-21 03:05:16

标签: android parcelable

我发布了一个关于将数据从活动传递到片段的问题。我已经了解到将Parcelable实现到POJO类是一种正确的方法。经过一些研究后我也明白,为了将数据传递给片段,应该使用Bundle而不是Intent。

我之前的问题 - > Using same fragments but different content in Android

但现在,我的问题是,在点击cardview时,如何使用set方法显示详细信息列表(姓名,地址,电话)?

要清楚,我想要的是

  • 点击第一家餐馆时,将启动包含详细信息片段的新意图。在详细信息片段中,它将显示第一家餐厅的餐馆名称,地址和电话。

当点击两个不同的餐厅cardview时,有人可以通过向我展示两组不同细节的代码来指导我吗?

RestaurantListAdapter.java

我想在onClick下使用if else语句,以便在点击不同的cardview时显示不同的详细信息

public class RestaurantListAdapter extends RecyclerView.Adapter<RestaurantListAdapter.ViewHolder>  {
    List<RestaurantList_Item> items;
    private static ClickListener clickListener;
    private Context context;

    public RestaurantListAdapter(){
        super();
        items = new ArrayList<RestaurantList_Item>();

        // POSITION 1
        RestaurantList_Item restaurant = new RestaurantList_Item();
        restaurant.setrImage(R.mipmap.img_anjappar);
        restaurant.setrName("Anjappar Indian Chettinad Restaurant");
        restaurant.setrCuisine("Indian");
        items.add(restaurant);

        // POSITION 2
        restaurant = new RestaurantList_Item();
        restaurant.setrImage(R.mipmap.img_morganfield);
        restaurant.setrName("Morganfield");
        restaurant.setrCuisine("Western");
        items.add(restaurant);

        // POSITION 3
        restaurant = new RestaurantList_Item();
        restaurant.setrImage(R.mipmap.img_nandos);
        restaurant.setrName("Nando's");
        restaurant.setrCuisine("Western");
        items.add(restaurant);

        // POSITION 4
        restaurant = new RestaurantList_Item();
        restaurant.setrImage(R.mipmap.img_shellout);
        restaurant.setrName("Shellout");
        restaurant.setrCuisine("Seafood");
        items.add(restaurant);

        // POSITION 5
        restaurant = new RestaurantList_Item();
        restaurant.setrImage(R.mipmap.img_beyond);
        restaurant.setrName("Beyond Veggie");
        restaurant.setrCuisine("Vegetarian");
        items.add(restaurant);

        // POSITION 6
        restaurant = new RestaurantList_Item();
        restaurant.setrImage(R.mipmap.img_myelephant);
        restaurant.setrName("My Elephant");
        restaurant.setrCuisine("Thai");
        items.add(restaurant);

        // POSITION 7
        restaurant = new RestaurantList_Item();
        restaurant.setrImage(R.mipmap.img_padangkota);
        restaurant.setrName("Nasi Kandar Padang Kota");
        restaurant.setrCuisine("Mamak");
        items.add(restaurant);

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.cardview_restaurant, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
        final RestaurantList_Item restaurant = items.get(position);
        viewHolder.resImage.setImageResource(restaurant.getrImage());
        viewHolder.restaurantName.setText(restaurant.getrName());
        viewHolder.cuisine.setText(restaurant.getrCuisine());
        viewHolder.itemView.setOnClickListener( new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Context context = v.getContext();
//                Toast.makeText(context, "Item clicked with position " +position, Toast.LENGTH_LONG).show();
                if(position == 0){
                    Intent i = new Intent(context, Restaurant.class);
                    context.startActivity(i);
                }
            }
        });
    }

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

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public ImageView resImage;
        public TextView restaurantName;
        public TextView cuisine;

        public ViewHolder(final View itemView) {
            super(itemView);
            resImage = (ImageView) itemView.findViewById(R.id.resImage);
            restaurantName = (TextView) itemView.findViewById(R.id.restaurantName);
            cuisine = (TextView) itemView.findViewById(R.id.cuisine);
            itemView.setOnClickListener(this);
        }


        @Override
        public void onClick(View v) {
            clickListener.onItemClick(getAdapterPosition(), v);
        }

    }

    public void setOnItemClickListener (ClickListener clickListener){
        RestaurantListAdapter.clickListener = clickListener;
    }

    public interface ClickListener{
        void onItemClick (int position, View v);
    }
}

RestaurantModel.java

这是包含get set方法的POJO类,我想使用set方法显示餐厅详细信息

public class RestaurantModel implements Parcelable{

    //empty constructor
    public RestaurantModel(){}

    //A constructor that initializes the Restaurant object
    public RestaurantModel(String resName, String resAddress, String resPhone, String resCuisine, String resPriceRange){
        this.resName = resName;
        this.resAddress =resAddress;
        this.resPhone = resPhone;
        this.resCuisine = resCuisine;
        this.resPriceRange = resPriceRange;
    }

    //Parcelling the object
    public RestaurantModel(Parcel in){
        String[] data = new String [5];
        in.readStringArray(data);
        this.resName = data[0];
        this.resAddress = data[1];
        this.resPhone = data[2];
        this.resCuisine = data[3];
        this.resPriceRange = data[4];

    }

    // variable main photo
    private int mainImage;

    //variables for details fragment
    private String resName, resAddress, resPhone, resCuisine, resPriceRange;

    //variables for menu fragment
    private int foodPhoto;
    private String foodPrice, foodDescription;

    /*get set methods*/
    public int getMainImage(){
        return mainImage;
    }

    public void setMainImage(int mainImage){
        this.mainImage = mainImage;
    }

    public String getResName(){
        return resName;
    }

    public void setResName(String resName){
        this.resName = resName;
    }

    public String getResAddress(){return resAddress;}

    public void setResAddress(String resAddress){this.resAddress = resAddress;}

    public String getResPhone(){return resPhone;}

    public void setResPhone(String resPhone){this.resPhone = resPhone;}

    public String getResCuisine(){return resCuisine;}

    public void setResCuisine(String resCuisine){this.resCuisine = resCuisine;}

    public String getResPriceRange(){return resPriceRange;}

    public void setResPriceRange(String resPriceRange){this.resPriceRange = resPriceRange;}

    public int getFoodPhoto(){return foodPhoto;}

    public void setFoodPhoto(int foodPhoto){this.foodPhoto = foodPhoto;}

    public String getFoodDescription(){return foodDescription;}

    public void setFoodDescription(String foodDescription){this.foodDescription = foodDescription;}

    public String getFoodPrice(){return foodPrice;}

    public void setFoodPrice(String foodPrice){this.foodPrice = foodPrice;}



    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[]{
                this.resName,this.resAddress,this.resPhone, this.resCuisine, this.resPriceRange
        });
    }

    // Creator
    public static final Parcelable.Creator<RestaurantModel> CREATOR = new Parcelable.Creator<RestaurantModel>(){
        @Override
        public RestaurantModel createFromParcel(Parcel source) {
            return new RestaurantModel(source);
        }

        @Override
        public RestaurantModel[] newArray(int size) {
            return new RestaurantModel[size];
        }
    };


}

Restaurant.java

此活动包含点击cardview时将显示的片段

public class Restaurant extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

    }

    private void setupViewPager(ViewPager viewPager){
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new details(), "Details");
        adapter.addFragment(new menu(), "Menu");
        adapter.addFragment(new tableBooking(), "Table booking");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter{

        private final List<Fragment> fragmentList = new ArrayList<>();
        private final List<String> fragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager){
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        public void addFragment (Fragment fragment, String title){
            fragmentList.add(fragment);
            fragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return fragmentTitleList.get(position);
        }
    }
}

Details.java

此类扩展包含餐馆详细信息的片段,例如姓名,地址和电话

public class details extends Fragment {

    private TextView resName, resAddress, resPhone, resCuisine, resPriceRange;

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


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

/*        resName = (TextView) getView().findViewById (R.id.resName);
        resAddress = (TextView) getView().findViewById (R.id.resAddress);
        resPhone = (TextView) getView().findViewById (R.id.resPhone);
        resCuisine = (TextView) getView().findViewById (R.id.resCuisine);
        resPriceRange = (TextView) getView().findViewById (R.id.resPriceRange);*/



    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_details, container, false);
    }

}

Homepage.java

public class Homepage extends Activity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager llm;
    RecyclerView.Adapter adapter;
    private static final String TAG = Homepage.class.getSimpleName();

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

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);

        llm = new LinearLayoutManager(Homepage.this);
        recyclerView.setLayoutManager(llm);

        adapter = new RestaurantListAdapter();
        recyclerView.setAdapter(adapter);

    }
}

编辑:我不确定我是否正确这样做。我创建了多个arraylist,描述了不同餐厅的不同细节。我把代码放在了RestaurantListAdapter中的onClick方法。

  @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
        final RestaurantList_Item restaurant = items.get(position);
        viewHolder.resImage.setImageResource(restaurant.getrImage());
        viewHolder.restaurantName.setText(restaurant.getrName());
        viewHolder.cuisine.setText(restaurant.getrCuisine());
        viewHolder.itemView.setOnClickListener( new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Context context = v.getContext();
                RestaurantModel rAnjappar = new RestaurantModel();
                details fragment = new details();
                Intent i = new Intent(context, Restaurant.class);

                // Array List
                ArrayList<RestaurantModel> a1 = new ArrayList<RestaurantModel>();
                rAnjappar.setResName("Anjappar");
                rAnjappar.setResAddress("Bandar Kinrara");
                rAnjappar.setResPhone("03-80807362");
                rAnjappar.setResCuisine("Mamak");
                rAnjappar.setResPriceRange("RM 30 for 2 person");

                ArrayList<RestaurantModel> a2 = new ArrayList<RestaurantModel>();
                rAnjappar.setResName("Morganfield");
                rAnjappar.setResAddress("Bandar Utama");
                rAnjappar.setResPhone("03-80807362");
                rAnjappar.setResCuisine("Western");
                rAnjappar.setResPriceRange("RM 60 for 2 person");

                // action when card view is clicked
                if(position == 0){
                    Bundle b1 = new Bundle();
                    b1.putParcelableArrayList("anjappar", a1);
                    fragment.setArguments(b1);
                    context.startActivity(i);

                }
            }
        });
    }

如果这是可以接受的,我接下来要做的就是在我的片段代码中检索包吗?但由于我将有多个捆绑包,我应该如何以正确的方式检索所有捆绑包?

2 个答案:

答案 0 :(得分:1)

您可以使用片段的setArguments()方法将您的餐厅模型类传递给新片段,同时创建它的新实例。您可以在新创建的片段{{1}中使用getArguments()将其取回}} 方法。您必须使您的resturantModel.java类可序列化。

onCreate()

添加数据: -

 public class RestaurantModel implements Serializable{
   ...
 }

获取数据:

   Bundle bundle = new Bundle();
   bundle.putSerializable("restaurant", restaurant);
   Fragment1 frag1 = new Fragment1();
   frag1.setArguments(bundle);

FYI: Parcelable和Serializable之间的区别:https://stackoverflow.com/a/3323554/4690731

答案 1 :(得分:1)

好的,据我所知,你可以做以下事情

1在适配器

中添加此方法
public RestaurantList_Item getItem(int pos) {
    return items.get(pos);
}

<强> 2。主页是您的clicklistner活动(希望如此)

public void onItemClick(int position, view v) {
        RestaurantList_Item row_object = adapter.getItem(position); 
        Intent i = new Intent(context, Restaurant.class);
        i.putExtra(Common.Data_Object, row_object);
        startActivity(i);

    }

第3。替换餐厅类的代码

public class Restaurant extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private RestaurantList_Item row_object;

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

        getIntentData(getIntent());

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

    }

    private void getIntentData(Intent i) {
        if (i != null) {

            row_object = i.getParcelableExtra(Common.Data_Object);
        }
    }

    private void setupViewPager(ViewPager viewPager){
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        Fragment f = new details();
        Bundle arguments = new Bundle();
        arguments.putParcelable(Common.Data_Object, row_object);
        f.setArguments(arguments);

        adapter.addFragment(f, "Details");
        adapter.addFragment(new menu(), "Menu");
        adapter.addFragment(new tableBooking(), "Table booking");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter{

        private final List<Fragment> fragmentList = new ArrayList<>();
        private final List<String> fragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager){
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        public void addFragment (Fragment fragment, String title){
            fragmentList.add(fragment);
            fragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return fragmentTitleList.get(position);
        }
    }
}

<强> 4。从详细信息片段中的包中获取对象

private void getIntentData(Bundle b)
{
    if (b != null)
    {
         detailObject = b.getParcelable(Common.Data_Object);
    }
}

希望它会有所帮助。