Use downloaded image in Xamarin Android Toolbar

jcus0006jcus0006 ✭✭Member ✭✭

To be able to display a logo on the right hand side of the navigation header bar of my Xamarin forms app (in the Android case), I am using this in the Toolbar.axml file of native Xamarin.Android project.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar 
xmlns:android=""
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="@style/ThemeOverlay.AppCompat.Light">

<RelativeLayout android:layout_width="wrap_content"
        android:layout_height="fill_parent">

<ImageView
android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter"
        android:src="@drawable/xlogo_small" 
        android:layout_gravity="right"
        android:layout_alignParentRight="true" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>

In the android:src, I am using xlogo_small image file, which needs to be in the drawables folder. Now I would have liked to have that file added into the drawables folder dynamically (from a web service call) during run-time. After a quick search I found out that adding files to the drawable folder is not possible during run-time.

I have also found that instead, in such a scenario, images are supposed to be saved into the internal memory. In the Xamarin Forms Shared project I can retrieve the logo via a web service call and save it into the: Environment.SpecialFolder.Personal directory.

I wish to know whether there is any way to refer to the path of a file stored in this internal storage directory, and use it instead of @drawable/xlogo_small within this line of Resources.axml:

android:src="@drawable/xlogo_small"

Any pointers?

Answers

  • jezhjezh Xamurai Member, Xamarin Team Xamurai

    @jcus0006

    Maybe you can try the following code.
    The below code is to set Bitmap images from a file stored inside a SD-Card .

            var image = FindViewById<ImageView>(Resource.Id.logo);
            File imgFile = new File("/sdcard/Images/test_image.jpg");
            if (imgFile.Exists())
            {
                Bitmap myBitmap = BitmapFactory.DecodeFile(imgFile.AbsolutePath);
                image.SetImageBitmap(myBitmap);
            }
    

    And include this permission in the manifest file:

      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    Note : From Android Marshmallow, you need to ask the user for the permissions.

  • jcus0006jcus0006 ✭✭ Member ✭✭

    Where do you put this code though?

Sign In or Register to comment.