简体   繁体   English

如何在同一活动的两个片段之间传递数据?

[英]How Do I Pass Data Between Two Fragments On The Same Activity?

在此处输入图像描述

Howdy, I'm working on a project and I'm running into some issues.你好,我正在做一个项目,但遇到了一些问题。 Namely, I have two fragments, each with their own adapter as both fragments are meant to be able to swipe horizontally.也就是说,我有两个片段,每个片段都有自己的适配器,因为这两个片段都是为了能够水平滑动。 A photo should be attached of the layout I have for further clarity.为了更清楚,应该附上我的布局的照片。 I would like to be able to tap the bottom fragment, which when I tap a place on the top fragment, the image I tapped or "Structure" will be placed down.我希望能够点击底部片段,当我点击顶部片段上的一个地方时,我点击的图像或“结构”将被放下。 However, what I can't figure out is how to smoothly transfer this data and if I were to do it through the activity, how do I do it as the activity has already run through all its code.但是,我想不通的是如何顺利传输这些数据,如果我要通过活动来完成,我该怎么做,因为活动已经运行了它的所有代码。 Could somebody please help, it would be greatly appreciated.有人可以帮忙吗,将不胜感激。

Main Activity主要活动

public class MainMap extends AppCompatActivity
{
    MapData data = MapData.get();
    StructureData structure = StructureData.get();

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

        FragmentManager frag = getSupportFragmentManager();    //To manage the map fragment
        MapCellFragment rv = (MapCellFragment) frag.findFragmentById(R.id.map);

        FragmentManager selectionFrag = getSupportFragmentManager();    //To manage the selection fragment
        SelectionCellFragment cf = (SelectionCellFragment) selectionFrag.findFragmentById(R.id.bar);

        if (rv == null)
        {
            rv = new MapCellFragment(data);
            frag.beginTransaction().add(R.id.map, rv).commit();
        }

        if (cf == null)
        {
            cf = new SelectionCellFragment(structure);
            selectionFrag.beginTransaction().add(R.id.bar, cf).commit();
        }
        
    }

Map Fragment Map 片段

    public MapData data;

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

    public MapCellFragment(MapData data)
    {
        this.data = data;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment gridCellFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MapCellFragment newInstance(String param1, String param2) {
        MapCellFragment fragment = new MapCellFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.map_fragment, container, false);
        RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
        rv.setLayoutManager(new GridLayoutManager(getActivity(), MapData.HEIGHT, GridLayoutManager.HORIZONTAL,false));
        MapAdapter myAdapter = new MapAdapter(data);
        rv.setAdapter(myAdapter);
        return view;
    }

Bottom Bar Fragment This was essentially a copy and paste of the other fragment, just changing the data which goes in and the XML it's attached to.底部栏片段这本质上是另一个片段的复制和粘贴,只是更改输入的数据和它所附加的 XML。

Map Adapter Map 适配器

package com.example.map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MapAdapter extends RecyclerView.Adapter<MapViewHolder>
{
    MapData data;

    public MapAdapter(MapData data)
    {
        this.data = data;
    }

    @NonNull
    @Override
    public MapViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.grid_cells,parent,false);

        //Resizes the images within the grid cells xml file
        int size = parent.getMeasuredHeight() / MapData.HEIGHT + 1;
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        lp.width = size;
        lp.height = size;

        MapViewHolder myViewHolder = new MapViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MapViewHolder holder, int position)
    {
        int row = position % MapData.HEIGHT;
        int col = position / MapData.HEIGHT;

        MapElement ele = data.get(row, col);

        holder.ne.setImageResource(ele.getNorthEast());
        holder.nw.setImageResource(ele.getNorthWest());
        holder.se.setImageResource(ele.getSouthEast());
        holder.sw.setImageResource(ele.getSouthWest());

        if(ele.getStructure() != null)
        {
            holder.mapStruct.setImageResource(ele.getStructure().getDrawableId());
        }

    }

    @Override
    public int getItemCount()
    {
        return 300;
    }

}

Map View Holder Map 视图支架

package com.example.map;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.Objects;

public class MapViewHolder extends RecyclerView.ViewHolder {
    ImageView nw;
    ImageView ne;
    ImageView sw;
    ImageView se;
    ImageView mapStruct;

    public MapViewHolder(@NonNull View itemView)
    {
        super(itemView);
        nw = itemView.findViewById(R.id.northWest);
        ne = itemView.findViewById(R.id.northEast);
        sw = itemView.findViewById(R.id.southWest);
        se = itemView.findViewById(R.id.southEast);
        mapStruct = itemView.findViewById(R.id.structure);

    }

}

Bar Adapter条形适配器

package com.example.map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SelectionAdapter extends RecyclerView.Adapter<SelectionViewHolder>
{
    StructureData data;

    public SelectionAdapter(StructureData data)
    {
        this.data = data;
    }

    @NonNull
    @Override
    public SelectionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.list_selection,parent,false);
        SelectionViewHolder myViewHolder = new SelectionViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull SelectionViewHolder holder, int position)
    {
        Structure s = data.get(position);
        holder.structure.setImageResource(s.getDrawableId());
        holder.label.setText(s.getLabel());
        holder.bind(s);
    }

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

Bar ViewHolder条形视图架

package com.example.map;

import android.annotation.SuppressLint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.Objects;

public class SelectionViewHolder extends RecyclerView.ViewHolder
{
    Structure selectObject;
    ImageView structure;
    TextView label;

    public SelectionViewHolder(@NonNull View itemView)
    {
        super(itemView);
        structure = itemView.findViewById(R.id.image);
        label = itemView.findViewById(R.id.label);

        structure.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                SelectionCellFragment.selectedData = selectObject;
            }

        });

    }

    public void bind(Structure s)
    {
        selectObject = s;
    }

    //Maybe, I need to place this bind function in MapViewHolder as well
    //When I press on the button, I must share the information over to the Map fragment
    //Then the new information will form a ImageView on the big one
}

You could use ViewModel to solve your use-case.您可以使用ViewModel来解决您的用例。 You could have something like SelectedStructureViewModel that will be set in the SelectionCellFragment when the user taps to select the structure.当用户点击 select 结构时,您可能会在SelectionCellFragment中设置类似SelectedStructureViewModel的内容。 While the MapCellFragment can observe this SelectedStructureViewModel to be notified whenever the user selects the structure.MapCellFragment可以观察到这个SelectedStructureViewModel以在用户选择结构时得到通知。 You can then query it when user taps a place on the Map.然后,您可以在用户点击 Map 上的位置时查询它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在属于同一容器活动的两个片段之间传递数据? - How can I pass data between two fragments belonging to same container activity? 如何将来自单独的AsyncTask内部类的两个结果传递给主活动中的相同方法? - How do I pass two results from separate AsyncTask inner classes to the same method in the main activity? 如何在FragmentPagerAdapter中的片段之间传递数据 - How to pass data between fragments in FragmentPagerAdapter Android - 如何在片段之间传递数据 - Android - How to pass data between fragments 如何在导航抽屉活动模板中的片段之间传递字符串变量 - How to pass string variable between fragments in navigation drawer activity template 如何在片段之间传递字符串? - How can I pass a String between fragments? 如何在 2 个片段之间传递值? - How can I pass values between 2 fragments? 如何在android java中使用intent切换到相同活动的两个片段 - How to switch to two fragments of the same activity using intent in android java 我该如何解决:多个片段和Activity_main之间的事务? - How do I fix: Transaction between multiple fragments and the Activity_main? 如何将登录按钮与包含两个片段的另一个活动连接 - How do i connect my login button with another activity containing two fragments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM