Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

CSharp:Android App - Appunti

From Aino Wiki

Jump to: navigation, search

Accesso al cloud Google

Doc

é Google Drive spiegazione ed esempio edandersen.com

Condivisione file

Visualizzazione di immagini

L'oggetto da usare è ImageView, si va ad agire sulle proprietà:

  • SetImageURI , per via programmatica oppure
  • android:src , nello XAML nel file xml di progettazione lato UI.

Per poter funzionare occorrerà impostare prima i diritti di accesso alle risorse del fileSystem. Vedere esempio qui (http://wiki.aino.it/index.php?title=CSharp:Android_App_-_primi_step#Permessi_.5C_Autorizzazioni Primi step autorizzazioni)

Esempio

Segue codice di esempio adattato da esempio preso su internet c-sharpcorner.com e che corrisponde al progetto di tipo xamarin native. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"  
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <TextView  
         android:id="@+id/TxtViewTitle"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:text="Android ImageView Example"  
         android:textSize="22sp"  
         android:textStyle="bold" />

    <ImageView
        android:id="@+id/ImageDocView"
        android:src="@android:drawable/ic_menu_compass"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center_horizontal"
        android:contentDescription="description" />

    <Button   
         android:id="@+id/BtnImgLoadCustom"
         android:text="Custom"  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content"  />  
    <Button    
         android:id="@+id/BtnFromGallery"
         android:text="From Galley"  
         android:layout_width="match_parent"  
         android:layout_height="wrap_content" />  
</LinearLayout>
using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Support.V7.App;
using Android.Widget;
using Bank_Document.Core;
using System;
using System.IO;
using System.Threading.Tasks;
 
namespace Bank_Document
{
    [Activity(Label = "@string/app_name"
                , Theme = "@style/AppTheme"
                , MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        public static readonly int PickImageId = 1000;
        TextView TxtViewTitle;
        ImageView ImageDocView;
        Button BtnImgLoadCustom;
        Button BtnFromGallery;
 
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
 
            //---Parte di personalizzazione
            TxtViewTitle = FindViewById<TextView>(Resource.Id.TxtViewTitle);
            ImageDocView = FindViewById<ImageView>(Resource.Id.ImageDocView);
            BtnImgLoadCustom = FindViewById<Button>(Resource.Id.BtnImgLoadCustom);
            BtnFromGallery = FindViewById<Button>(Resource.Id.BtnFromGallery);
 
            BtnImgLoadCustom.Click += BtnImgLoadCustom_Click;
            BtnFromGallery.Click += BtnFromGallery_Click;
 
            InitializeCustom();
        }
 
        private void InitializeCustom()
        {
            bool isAccessDenied = false;
            string strErrorMsg = string.Empty;
            int nrAttempt4Access = 0;
 
            try
            {
                do
                {
                    strErrorMsg = string.Empty;
                    if (ContextCompat.CheckSelfPermission(this
                                , Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
                    {
                        strErrorMsg += "\r\nMissed read permission for external archive";
                        isAccessDenied = true;
                    }
                    if (ContextCompat.CheckSelfPermission(this
                                , Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
                    {
                        strErrorMsg += "\r\nMissed write permission for external archive";
                        isAccessDenied = true;
                    }
                    if (isAccessDenied)
                    {
                        var permissions = new string[]
                                            {
                                                Manifest.Permission.ReadExternalStorage,
                                                Manifest.Permission.WriteExternalStorage
                                            };
                        // RequestCode REQUEST_FOLDER_PERMISSION = 9?
                        ActivityCompat.RequestPermissions(this, permissions, 9);
 
                        Task.Delay(4000).Wait(); //Attesa di 4 secondi
                        isAccessDenied = ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted
                                    || ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted;
                    }
                } while (isAccessDenied && nrAttempt4Access < 3);
                if (isAccessDenied && nrAttempt4Access == 3)
                {
                    throw new Exception("Permissions are mandatory!\r\n" + strErrorMsg);
                }
            }
            catch (System.Exception ex)
            {
                AManager.MessageBox(this, "InitializeCustom", ex.Message);
            }
        }
 
        private void BtnFromGallery_Click(object sender, System.EventArgs e)
        {
            try
            {
                Intent = new Intent();
                Intent.SetType("image/*");
                Intent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture")
                                    , PickImageId);
            }
            catch (System.Exception ex)
            {
                AManager.MessageBox(this, "BtnFromGallery", ex.Message);
            }
        }
 
        // Create a Method OnActivityResult(it is select the image controller)   
        protected override void OnActivityResult(int requestCode, Result resultCode
                                               , Intent data)
        {
            if ((requestCode == PickImageId) 
                && (resultCode == Result.Ok) 
                && (data != null))
            {
                Android.Net.Uri uri = data.Data;
                string strFileName = Path.GetFileName(uri.Path);
                TxtViewTitle.Text = strFileName;
                ImageDocView.SetImageURI(uri);
            }
        }
 
        private void BtnImgLoadCustom_Click(object sender, System.EventArgs e)
        {
            try
            {
                string rootPath = "/storage/emulated/0/";
                string relativePath = "MiaCartella/Doc/fileImmagine.jpg";
                Java.IO.File fileImage = new Java.IO.File(rootPath + relativePath);
 
                Android.Net.Uri uri = Android.Net.Uri.FromFile(fileImage);
                ImageDocView.SetImageURI(uri);
            }
            catch (System.Exception ex)
            {
                AManager.MessageBox(this, "BtnImgLoadCustom", ex.Message);
            }
        }
 
        //etc... non serve
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions
                                , [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions
                                                                , grantResults);
 
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

Si usa un metodo preconfezionato per invocare l'Esplora risorse standard di Android affinché si scelga il file immagine da visualizzare, allo scopo c'è un modo per creare un metodo "Action" preconfezionata, notare i metodi BtnFromGallery_Click (che è l'hadler personalizzato di preparazione) ma soprattutto OnActivityResult!

QR Code

Accesso a Risorse

FingerPrint

Share

La condivisione di risorse con altre App:

Mappa e Link


C# | Android App


Visual Studio | Windows Form | MS SQL | Dizionario


Parole chiave:

Author