findViewById 在静态函数中不起作用 [英] findViewById not working in static function

查看:53
本文介绍了findViewById 在静态函数中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found error in findViewById in static function.

我的功能是——

public static void onYearSelect() {

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

}

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

is there any way to solve this error!

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

推荐答案

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

You need to add view inside function as parameter.

public static void onYearSelect(View view) {

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

}

包含布局数据的视图.

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

When you call that function add onYearSelect(rootView) here rootView have the layout view.

编辑 1:

这里的视图是什么?

Android 中的视图是显示某些内容的小部件.按钮、列表视图、图像视图等都是 View 的子类.当您说更改视图"时,我假设您的意思是使用 setContentView() 更改布局.这通常每个活动只需要执行一次.Activity 基本上就是你所说的屏幕.

您可以在此处阅读更多内容.

You can read more here.

这篇关于findViewById 在静态函数中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆