When to use getString ()

I'm curious about getString (). I see what works getString(R.string.some_text). Also works getResources().getString(R.string.connection_error). So my question is why should we use getString or when? Thanks!

+4
source share
5 answers

The question is easily misunderstood.

If you are in a valid context (e.g. Activity), there is no difference because the context has a link to resources, so it can directly resolve getString(int);which string returns.

Adding more information for your peace of mind.

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 , " ", .

Activity getString():

.

, , , Resources be stripped of any styled text information. Resources , . Activity - :)

+5

. , . , :

public final String getString(int resId) {
 return getResources().getString(resId);
 }

, , , getResources() . getString() .

+2

TextView, setText(). ( CharSequence), (int resId). .

, strings.xml getResources(). getString (int resId) . .

+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`

Android, . , , Context, , getString , , , , , , , , , getContext().getResources().getString(R.string.connection_error)

, .

+1

All Articles