如何在我的主 class 中使用 Fragment 的 Spinner 事件?

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

下面名为Presenteter的代码是我的主要class,我正在根据问题替换Fragment

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

这是我的Questionsclass。它正在从 REST 服务器获取问题。所有问题都列在一个 Spinner 中。为了不让大家误会,就不写在这里了。

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

最后我想在我的 Presenter class.

中使用 SpinneronItemSelected() 事件

我该怎么做? 提前致谢。

您可以在 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) {

    }
});

很高兴您的问题得到了解答,但还有更好的方法。

如果您熟悉 Rx 的东西,这是一种方法。

如果 Rx 不是你的菜,你可以使用 EventBus 来简化这种通信。 Link: EventBus

如果你不确定,我建议你选择后者。