seyid yagmur seyid yagmur - 5 months ago 13
Java Question

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.

Answer

You could do something like this:

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

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

    }
});