0

TextView挿入されるテキストを変更するサブクラスを作成しています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"/>

を呼び出すと NullPointerException が発生しcontext.getApplicationContext()ます。

誰かがすでにこれに出くわしましたか?

4

3 に答える 3

1

これを試してみるべきだと思います:

this.getContext().getApplicationContext()

これはヌルポインタ例外を返すべきではありません。

于 2013-04-18T15:28:48.020 に答える
0

以下のリンクをチェックして、いつ getApplicationContext() を使用するか、いつ Activity Context を使用するかを確認してください

アクティビティ コンテキストまたはアプリケーション コンテキストをいつ呼び出すか?

ほとんどの場合、Activity コンテキストを使用する方が適切です

于 2013-04-18T15:21:37.483 に答える
0

ローカライズの方法が間違っています。以下のリンクを確認してください: http://developer.android.com/guide/topics/resources/localization.html

于 2013-04-18T15:23:33.063 に答える