【问题标题】:How can I use Fragment's Spinner events in my main class?如何在我的主类中使用 Fragment 的 Spinner 事件?
【发布时间】:2016-06-30 21:21:30
【问题描述】:

下面名为Presenteter的代码是我的主类,我根据问题替换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();
}

这是我的Questions 课程。它正在从 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 类中使用SpinneronItemSelected() 事件。

我该怎么做? 提前致谢。

【问题讨论】:

    标签: java android spinner onitemclicklistener


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      很高兴您的问题得到解答,但有更好的方法可以做到这一点。

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

      如果 Rx 不是您的菜,您可以使用 EventBus,它可以简化这种通信。 关联: EventBus

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

      【讨论】:

      • 非常感谢,我不太擅长 android,甚至还不是小学生 :),但我喜欢你告诉我的它们。我相信我会在其余的应用程序中使用它们。 :)
      • 很高兴能帮到你。 EventBus 有时确实是救星,但随着你学得越来越多,你会找到其他方法来解决这种情况。
      猜你喜欢
      • 2018-04-10
      • 1970-01-01
      • 2019-04-27
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多