Android 在TextView.setText()中获取applicationContext
我正在构建一个Android 在TextView.setText()中获取applicationContext,android,nullpointerexception,textview,subclass,Android,Nullpointerexception,Textview,Subclass,我正在构建一个TextView子类来更改插入到android:text中的文本。例如,我想将整个文本大写,但为了确保需要,我需要访问应用程序实例(我有一个布尔值,告诉它是否必须大写) 我实现了这个子类: public class UpperTextView extends TextView { private Context context; public UpperTextView(Context context) { super(context); this.contex
TextView
子类来更改插入到android:text
中的文本。例如,我想将整个文本大写,但为了确保需要,我需要访问应用程序实例(我有一个布尔值,告诉它是否必须大写)
我实现了这个子类:
public class UpperTextView extends TextView {
private Context context;
public UpperTextView(Context context) {
super(context);
this.context = context;
}
public UpperTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
public UpperTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
@Override
public void setText(CharSequence text, BufferType type) {
//I get a NullPointerException here since var context is null
Context applicationContext = context.getApplicationContext();
if (text != null && applicationContext instanceof MyApplication && applicationContext.doUppercase()) {
MyApplication myApp = (MyApplication) applicationContext;
myApp.getLanguagesController().getLocalizedString(text.toString().toUpperCase());
}
super.setText(text, type);
}
}
在布局中,我这样声明它
<my.package.UpperTextView
android:id="@+id/foo"
android:text="bar"/>
调用context.getApplicationContext()
时,我得到一个NullPointerException
是否有人遇到过此问题?查看下面的链接,了解何时使用getApplicationContext()以及何时使用活动上下文
大多数情况下,最好使用活动上下文这是不正确的本地化方法。查看以下链接:
我想你应该试试这个:
this.getContext().getApplicationContext()
这不应返回空指针异常 您不需要跟踪上下文,您可以在ViewThing中调用getContext,事务由服务器提供。。。因此,我无法将资源文件夹用于它