我们应该如何在 Android 中设置小部件值?

How should we set widgets values in Android?

我在查看我的代码时发现至少有 3 种方法可以在代码中获取小部件的引用:

第一个(onCreate 之前):

private TextView textView= (TextView) findViewById(R.id.textView);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
    }

第二个(在onCreate中):

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        final TextView textView= (TextView) findViewById(R.id.textView);
     }

第三个(创建出来并在onCreate中设置):

private TextView textView;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_layout);

            textView= (TextView) findViewById(R.id.textView);
         }

这3种方法有什么区别?我应该什么时候使用它们?

第一个不保证你的widget真的被实例化了,它不在onCreate里面。

第二个将被实例化,但它的值不能改变,因为它成为一个常量,成为最终的。

第三,它是一个全局变量,将在 onCreate 中实例化,您可以在代码的任何其他部分使用它。

如果您需要调用 findViewById(),那么调用应该在 setContentView 之后的任何位置。不像你的第一个选项那样。您的第三个选项创建一个实例变量,仅当在整个 class 期间大量访问 textview 时才使用它,否则只需在需要的地方调用 findViewById

您必须在调用 findViewById() 之前调用 setContentView(),因此第一种方法将始终为您提供 null。除了 final 关键字外,第二个和第三个相同,但这是 Java feature,而不是 Android。