【问题标题】:findViewById not working in static functionfindViewById 在静态函数中不起作用
【发布时间】:2016-07-30 07:43:55
【问题描述】:

我在静态函数的findViewById 中发现错误。

我的功能是——

public static void onYearSelect() {

    Spinner yearSelector;
    String yearName;
    yearSelector = (Spinner) findViewById(R.id.year_submit);
    yearName = yearSelector.getSelectedItem().toString();

}

有什么办法可以解决这个错误!

我可以在 yearName 中将 Spinner 的值存储为字符串

【问题讨论】:

    标签: java android android-studio


    【解决方案1】:

    您需要在函数内添加视图作为参数。

    public static void onYearSelect(View view) {
    
        Spinner yearSelector;
        yearSelector = (Spinner) view.findViewById(R.id.year_submit);
        yearName = yearSelector.getSelectedItem().toString();
    
    }
    

    The view which contains your layout data.

    当您调用该函数时,在此处添加onYearSelect(rootView) rootView 具有布局视图。

    编辑 1:

    这里的视图是什么?

    A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.

    您可以阅读更多here

    【讨论】:

      【解决方案2】:

      在微调器对象上设置 setOnItemSelectedListener 并在 onItemSelected() 内设置 yearName 的值。如下所示,

      yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
       String yearName = parentView.getItemAtPosition(position).toString()
      }
      
      @Override
      public void onNothingSelected(AdapterView<?> parentView) {
          // your code here
      }});
      

      【讨论】:

        猜你喜欢
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        • 2018-10-09
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多