开发者

Android toString method in static context

So far i've been writing my Android app just by typing names in to methods. I am now sorting this out, going through and putting these into string.xml instead and referencing the string using:

txt.setText(this.getString(R.string.string_name));

However, when trying to use this in a static context (in public static void), it does not work and gives an error.

Does anyone have any pointers of how to overcome this? I am fairly new to Java/Android programming and this is the first time I have come across 开发者_运维知识库this problem. Any help is much appreciated.

Extra code:

public static void ShowCatAddedAlert(Context con)
{
AlertDialog.Builder builder=new AlertDialog.Builder(con);
builder.setTitle("Add new Category");
builder.setIcon(android.R.drawable.ic_dialog_info);
DialogListner listner=new DialogListner();
builder.setMessage("Category Added successfully");
builder.setPositiveButton("ok", listner);

AlertDialog diag=builder.create();
diag.show();

}


Assuming that txt is a TextView, then you can just do txt.setText(R.string.string_name). You can usually reference to a string by it's resource id rather than getting it explicitly. More on that http://developer.android.com/guide/topics/resources/string-resource.html


String resources, as all resources, are resolved from the application from a Context instance (usually that's an Activity instance or the Application instance). In a static context, you don't have any instances unless you pass them in to your static methods.

One way or another, you need to do something in a non static context. Either you keep a copy of the Resources object around and pass it to your static methods, or you pass a Context instance around that is capable of resolving your resources, or you have a static Resources object that gets set at some point before your static methods get called.

That being said, you might want to revisit whether or not you absolutely need these methods to be static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜