繁体   English   中英

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

[英]How Do I Pass Data Between Two Fragments On The Same 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 片段

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

底部栏片段这本质上是另一个片段的复制和粘贴,只是更改输入的数据和它所附加的 XML。

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 视图支架

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

    }

}

条形适配器

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

条形视图架

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
}

您可以使用ViewModel来解决您的用例。 当用户点击 select 结构时,您可能会在SelectionCellFragment中设置类似SelectedStructureViewModel的内容。 MapCellFragment可以观察到这个SelectedStructureViewModel以在用户选择结构时得到通知。 然后,您可以在用户点击 Map 上的位置时查询它。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM