简体   繁体   English

将微调值从片段传递到活动

[英]Passing spinner value from fragment to activity

I'm trying to send the value of the spinner from the fragment to the Main activity, trying to use intent to do so, but it's not working really.我正在尝试将微调器的值从片段发送到主要活动,并尝试使用意图来这样做,但它并没有真正起作用。 I am using toast in the main activity to check if the value is passing but it isn't我在主要活动中使用 toast 来检查值是否正在传递,但事实并非如此

Any help?有什么帮助吗?

Fragment Code:片段代码:

  View rootView = inflater.inflate(R.layout.fragment_language, container, false);
    Spinner spinner = (Spinner) rootView.findViewById(R.id.language_Spinner);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            // this line will get you the selected item of the spinner
            String selectedValue = parent.getItemAtPosition(position).toString();
            Intent i = new Intent(getActivity(), MainActivity.class);
            Intent i1 = new Intent(getActivity(), PetsActivity.class);
            i.putExtra("languageValue", selectedValue);
            i1.putExtra("languageValue", selectedValue);

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent)
        {
        }
    });
    return rootView;

}

Main Activity主要活动

String languageChoice = getIntent().getStringExtra("languageValue");

    Toast.makeText(this, languageChoice, Toast.LENGTH_SHORT).show();

But obviously it's not working.但显然这是行不通的。

How can I fix this?我怎样才能解决这个问题?

If this fragment is a part of that activity, then you don't need to have an intent如果这个片段是那个活动的一部分,那么你不需要有一个意图

you can create a method in your activity assume you name it getSpinnerValue(String value) .您可以在活动中创建一个方法,假设您将其命名为getSpinnerValue(String value) Then in your fragment use getActivity() or requireActivity() , cast it to your activity class, and call getSpinnerValue(value)然后在您的片段中使用getActivity()requireActivity() ,将其投射到您的活动 class,然后调用getSpinnerValue(value)

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        // this line will get you the selected item of the spinner
        String selectedValue = parent.getItemAtPosition(position).toString();
        ((MainActivity) getActivity()).getSpinnerValue(selectedValue);

        // ... reset of code

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

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