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

时间:2019-05-21 01:56:58

标签: android android-fragments fragment android-fragmentactivity

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


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


    }
}

编译时没有任何错误,但应用程序不断崩溃。 我现在很着急:'(

1 个答案:

答案 0 :(得分:0)

我可以提出一个简单的解决方案,用于在附加到父活动的片段之间共享变量:

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

希望这会有所帮助。