繁体   English   中英

在TextView.setText()中获取applicationContext

[英]get applicationContext in TextView.setText()

我正在构建一个TextView子类,以更改android:text插入的android:text 例如,我想将整个文本大写,但是为了确保需要,我需要访问Application实例(我有一个布尔值,告诉它是否必须大写)。

我实现了这个子类:

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。

有人遇到过这个吗?

我认为您应该尝试这样做:

this.getContext().getApplicationContext()

这不应返回空指针异常。

检查下面的链接以了解何时使用getApplicationContext()以及何时使用活动上下文

何时调用活动上下文或应用程序上下文?

在大多数情况下,最好使用Activity上下文

这是不正确的本地化方式。 检查以下链接: http : //developer.android.com/guide/topics/resources/localization.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM