简体   繁体   中英

Android: How to set the ImageView src from string?

I am very beginner in java, please help. I have an android app source code. My default imageView is like this:

<ImageView
        android:id="@+id/flag_logo"
        android:layout_marginBottom="@dimen/global_keyline_s"
        android:scaleType="fitCenter"
        android:src="@drawable/flag_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:cropToPadding="false"
        android:adjustViewBounds="true" />

I need to translate my app in some country, and I need to set dynamically the app title and the flag icon.

I have string resources and already translated:

<resources>
    <string name="app_name">My App Name</string>
    <string name="flag_icon">@drawable/flag_icon</string>
    ...
</resources>

In ImageVeiw, can I change:

android:src="@drawable/flag_icon" to android:src="@string/flag_icon" ?

When I test this script to an emulator it is ok, but when I try to generate to signed apk I got error:

Error:(4) Error: Unexpected resource reference type; expected value of type @string/ [ReferenceType]

I've been looking for this issue but have not yet found, please help. thanks.

I think your approach is a bad idea.

You can localize a drawable too. I think this is the better approach for changing images when localizing your app.

In ImageVeiw, can I change:

android:src="@drawable/flag_icon" to android:src="@string/flag_icon" ?

No you cant. What @drawable/flag_icon means is that the drawable flag_icon is located int the drawable folder(s). Unless you have a folder with the name string , that path is invalid

As far as localization is concerned, only some specific res folders can be localized. More information about it here .

For drawable you should use something like drawable-[language code]-r[capitalized localization code] .

And, your approach won't work (read isn't working ) because of data value mismatch. @drawable returns int .

Just like @glethien suggested. I would use localized drawables - https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources

So you put your image in drawable-hdpi and drawable-de-hdpi and based on device language it will take appropriate resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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