gpt4 book ai didi

java - getResources 作为全局变量

转载 作者:行者123 更新时间:2023-12-02 05:33:09 25 4
gpt4 key购买 nike

我有简单的 Activity :

public class TestActivity extends MainActivity {    
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.test);

final Button click = (Button) findViewById(R.id.ButtonSave);

click.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Resources resources = getResources();
String text = resources.getString(R.string.test);
Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT).show();
}
});

final Button click2 = (Button) findViewById(R.id.ButtonSave);

click2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Resources resources = getResources();
String text = resources.getString(R.string.test2);
Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT).show();
}
});
}
}

这工作得很好,但我正在学习 Android,我想修改它。我想使用 getResources 作为全局变量:

public class TestActivity extends MainActivity {    

Resources resources = getResources(); //ADD HERE!

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.test);

final Button click = (Button) findViewById(R.id.ButtonSave);

click.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
//REMOVE!
String text = resources.getString(R.string.test);
Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT).show();
}
});

final Button click2 = (Button) findViewById(R.id.ButtonSave);

click2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
//REMOVE!
String text = resources.getString(R.string.test2);
Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT).show();
}
});
}
}

但这会返回主要异常。为什么?我怎样才能做到?

最佳答案

不需要将其作为全局实例,它已经绑定(bind)到 Activity,您可以通过调用其名称直接从 Activity 获取其实例。

示例:

click.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
String text = TestActivity.this.getResources().getString(R.string.test);
Toast.makeText(TestActivity.this, text, Toast.LENGTH_SHORT).show();
}
});

无需将其分配给 getResource 将返回其相同实例的变量。因此不必将其声明为全局变量。

第二段代码失败,因为您在 Activity 的 onCreate() 之前直接获取 getResources() ,从而捕获了异常。

关于java - getResources 作为全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25316151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com