简体   繁体   中英

How can I use Fragment's Spinner events in my main class?

the code below named Presenteter is my main class, and I am replacing the Fragment according to questions.

public class Presenteter extends AppCompatActivity   {
    private final Questions question1Fragment = new Questions();
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.present);

FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out);

         ft.replace(R.id.flPersonalization, question1Fragment);

        ft.commit();
}

This is my Questions class. It is getting the questions from REST server. All questions are listed in in one Spinner . I didn't write them here, in order not to confuse you.

public class Questions extends Fragment implements AdapterView.OnItemSelectedListener {
    SearchableSpinner spinner;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.question, container, false);
  LinearLayout ln=(LinearLayout)view.findViewById(R.id.listLayout);
          spinner=(SearchableSpinner)view.findViewById(R.id.spinner1);
}

Finally I want to use Spinner 's onItemSelected() event in my Presenter class.

How can I do this? Thanks in advance.

You could do something like this in your Fragment :

Presenteter p = (Presenteter) getActivity();

// ...

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        p.yourMethod(); // call a method of your Presenteter class
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});

I'm glad your question is answered but there is a better way for doing this.

If you are familiar with Rx stuff, that's one way to do it.

If Rx is not your cup of tea, you can use EventBus which simplifies exactly this kind of communication. Link: EventBus

I would suggest going for the latter if you are not sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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