gpt4 book ai didi

android - 使用 set 方法将数据从 Activity 发送到 Fragment

转载 作者:太空狗 更新时间:2023-10-29 13:14:01 26 4
gpt4 key购买 nike

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

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

但是现在,我的问题是,我应该怎么做才能在单击卡片 View 时使用设置方法显示详细信息列表(姓名、地址、电话)?

说清楚,我想要的是

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

谁能指导我点击两个不同的餐厅卡片 View 时显示两组不同详细信息的代码?

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];
}
};


}

餐厅.java

此 Activity 包含单击卡片 View 时将显示的 fragment

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);
}
}
}

详细信息.java

此类扩展了包含餐厅详细信息(例如名称、地址和电话)的 fragment

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);
}

}

首页.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);

}
}

编辑:我不确定我这样做是否正确。我创建了多个数组列表来描述不同餐厅的不同细节。我将代码放在 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);

}
}
});
}

如果这是可以接受的,接下来我应该做的是在我的 fragment 代码中检索包,对吗?但由于我将拥有多个 bundle ,我应该如何以正确的方式检索所有 bundle ?

最佳答案

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

1 在Adapter中添加此方法

public RestaurantList_Item getItem(int pos) {
return items.get(pos);
}

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

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。替换 Restaurant 类的代码

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。从 Detail fragment 中的 bundle 中获取对象

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

希望对您有所帮助。

关于android - 使用 set 方法将数据从 Activity 发送到 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36758864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com