在同一 activity 中的片段之间进行通信

Communicating between fragments in a same activity

我是 Android 的新手,正在开发一个应用程序以在单个 activity 中显示两个片段之间的通信。当我从第一个片段中的自定义列表视图中单击一个项目时,第二个片段中的视图在运行时发生变化。


public class FirstFragment extends Fragment {
onSelectedCitySendListener selectedCitySendListener;
    public interface onSelectedCitySendListener{


    public void onSelectedCitySend(int city) ;

    }


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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_first, container, false);
        String[] cities = {"Kamloops", "Calgary", "Toronto","Vancouver"};
        ListView listView = (ListView) view.findViewById(R.id.cityList);
        ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, cities);
        listView.setAdapter(listViewAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int pos = position;
                selectedCitySendListener.onSelectedCitySend(pos);
            }
        });

        // Inflate the layout for this fragment
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity)context;
        selectedCitySendListener = (onSelectedCitySendListener) activity;
    }


}

public class SecondFragment extends Fragment {


    public SecondFragment() {
        // Required empty public constructor
    }
private static TextView textView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second, container, false);
        textView =  view.findViewById(R.id.frameLayout2);
        Bundle bundle = getArguments();
        int position = bundle.getInt("Position");
        if(position == 0)
            textView.setText("Kamloops is a Canadian city in British Columbia, where the North and South Thompson rivers meet. Sun Peaks Resort’s hiking trails, bike park and numerous ski runs lie to the northeast. Cougars and bears inhabit the British Columbia Wildlife Park east of town. West, above Kamloops Lake are clay hoodoos (or spires). The riverside Secwepemc Museum & Heritage Park features the remains of a 2,000-year-old village.");
        if(position == 1)
            textView.setText("Calgary, a cosmopolitan Alberta city with numerous skyscrapers, owes its rapid growth to its status as the centre of Canada’s oil industry. However, it’s still steeped in the western culture that earned it the nickname “Cowtown,” evident in the Calgary Stampede, its massive July rodeo and festival that grew out of the farming exhibitions once presented here.");
        if(position == 2)
            textView.setText("Toronto, the capital of the province of Ontario, is a major Canadian city along Lake Ontario’s northwestern shore. It's a dynamic metropolis with a core of soaring skyscrapers, all dwarfed by the iconic, free-standing CN Tower. Toronto also has many green spaces, from the orderly oval of Queen’s Park to 400-acre High Park and its trails, sports facilities and zoo.");
        if(position == 3)
            textView.setText("Vancouver, a bustling west coast seaport in British Columbia, is among Canada’s densest, most ethnically diverse cities. A popular filming location, it’s surrounded by mountains, and also has thriving art, theatre and music scenes. Vancouver Art Gallery is known for its works by regional artists, while the Museum of Anthropology houses preeminent First Nations collections.");

        return view;

    }


}
public class MainActivity extends AppCompatActivity implements FirstFragment.onSelectedCitySendListener {

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


        FirstFragment firstFragment = new FirstFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, firstFragment).commit();
        SecondFragment secondFragment = new SecondFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.frameLayout2, secondFragment).commit();
    }


    @Override
    public void onSelectedCitySend(int pos) {
    Bundle bundle = new Bundle();
    bundle.putInt("Position", pos);
    SecondFragment secondFragment = new SecondFragment();
    secondFragment.setArguments(bundle);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout2, secondFragment, null);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();


    }
}

编译时没有任何错误,但应用程序一直崩溃。 我现在很恐慌:'(

我可以建议一个简单的解决方案,用于在附加到父级的片段之间共享变量 activity:

在 MainActivity 中创建一个静态变量(该变量对于 MainActivity 的所有实例都是通用的):

private static int position = 0;

在 MainActivity 中为其创建一个 setter 和一个 getter:

int getPosition() { return position; }
void setPosition(int position) { this.position = position; }

在您的 FirstFragment 中,将变量的值设置为您想要的值(例如在 OnClickEventListener 中):

((MainActivity)requireActivity()).setPosition(1);

在您的 SecondFragment 中,随时检索变量的值(例如在 onCreate() 中,但在 onResume() 中可能更好):

((MainActivity)requireActivity()).getPosition();

希望这对您有所帮助。