6

getString() について疑問に思っています。私は仕事をすることがわかりますgetString(R.string.some_text)。また、getResources().getString(R.string.connection_error)動作します。私の質問は、なぜ getString を使用する必要があるのか​​、またはいつ使用する必要があるのか​​ということです。ありがとう!

4

5 に答える 5

5

この質問は誤解されやすいです。

有効なコンテキスト (アクティビティなど) にいる場合、違いはありません。コンテキストにはリソースへの参照があるためgetString(int);、文字列を返す直接解決できるからです。

安心のために情報を追加します。

getString を直接使用できる場合は、そのまま実行してください。多くのヘルパー メソッドが含まれているため、 getResources() を使用する必要がある場合があります。

の Android ソース コードは次のgetResources.getString()とおりです。

/**
     * Return the string value associated with a particular resource ID.  It
     * will be stripped of any styled text information.
     * {@more}
     *
     * @param id The desired resource identifier, as generated by the aapt
     *           tool. This integer encodes the package, type, and resource
     *           entry. The value 0 is an invalid identifier.
     *
     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
     *
     * @return String The string data associated with the resource,
     * stripped of styled text information.
     */
    public String getString(int id) throws NotFoundException {
        CharSequence res = getText(id);
        if (res != null) {
            return res.toString();
        }
        throw new NotFoundException("String resource ID #0x"
                                    + Integer.toHexString(id));
    }

きちんとね?:)

実のところ、Resources オブジェクトは単に「文字列を取得する」だけではありません。こちらをご覧ください。

getString()の Activity バージョンと比較してみましょう:

アプリケーションのパッケージのデフォルト文字列テーブルからローカライズされた文字列を返します。

要約するbe stripped of any styled text information.と、Resources オブジェクトができることと、Resources オブジェクトがさらに多くのことを実行できるという事実を除けば、最終結果は同じです。アクティビティ バージョンは便利なショートカットです :)

于 2013-12-12T09:07:45.363 に答える
1

TextView に使用する場合、2 つのメソッド setText() があります。1 つは (CharSequence 文字列) を取り、もう 1 つは (int resId) を取ります。そのため、両方のバリアントが機能します。

一般的に、strings.xml ファイルですべての文字列を定義し、コードで getResources().getString(int resId) を介して取得することをお勧めします。このアプローチがあれば、アプリを簡単にローカライズできます。アプリのリソースについて詳しくは、こちらをご覧ください

于 2013-12-12T09:02:44.263 に答える
1

非常に基本的な違い。

R.string.some_text = return ID integer, identifying string resource in your space
getResources().getString(R.string.connection_error) = Will return you actualy string associated with ID `R.string.connection_error`

どちらも、多くのウィジェットがリソースの ID または値を直接取得できる Android システムで使用できます。実際には、返される値に違いはありません。唯一の違いは TermContextです。アクティビティ コンテキストを利用できるため、このコンテキストのリソースへのルートを直接呼び出すことができますgetString。一方、コンテキストが利用できないクラスからは、たとえばアダプタから、次のようにする必要があります。最初にコンテキストにアクセスし、次にコンテキストに関連付けられたリソースにアクセスし、最後に文字列にアクセスするので、次のように記述しますgetContext().getResources().getString(R.string.connection_error)

混乱が解消されることを願っています。

于 2013-12-12T09:05:12.887 に答える
0

正当な理由の 1 つは、次のような書式設定とスタイリングに関するものです:( http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling )

于 2013-12-12T09:07:52.373 に答える