Как связать изображения из галереи с imageView во время выполнения? - PullRequest
0 голосов
/ 04 марта 2020

У меня есть домашнее задание о создании клона WhatsApp. Но у меня есть проблема. У меня есть экран добавления контакта. Пользователи выбирают изображение из галереи и вводят свое имя. Когда они нажимают кнопку добавления, элемент списка будет добавлен в чат. Снимок экрана ниже. У меня есть класс person, такой как:

public class Person
{
private int id;
private string name;
private int imageId;

public Person(int id, string name, int imageId)
{
    this.id = id;
    this.name = name;
    this.imageId = imageId;

}


public int Id   // property
{
    get { return id; }   // get method
    set { id = value; }  // set method
}

public string Name   // property
{
    get { return name; }   // get method
    set { name = value; }  // set method
}


public int ImageId   // property
{
    get { return imageId; }   // get method
    set { imageId = value; }  // set method
}

public static explicit operator Java.Lang.Object(Person v)
{
    throw new NotImplementedException();
}

}

public class PersonAdapter : BaseAdapter
{
private LayoutInflater mInflater;
private List<Person> personArrayList;

public PersonAdapter(Activity activity, List<Person> personArrayList)
{

    this.mInflater = (LayoutInflater)activity.GetSystemService(Context.LayoutInflaterService);
    this.personArrayList = personArrayList;
}

public override int Count => personArrayList.Count;

public override Object GetItem(int position)
{
    return (Object)personArrayList.ElementAt(position);
}

public override long GetItemId(int position)
{
    return position;
}

public override View GetView(int position, View convertView, ViewGroup parent)
{
    convertView = mInflater.Inflate(Resource.Layout.List_Item, null);
    TextView personName = (TextView)convertView.FindViewById(Resource.Id.name);
    TextView personMessage = (TextView)convertView.FindViewById(Resource.Id.message);
    ImageView personImage = (ImageView)convertView.FindViewById(Resource.Id.imageView);
    Person person = personArrayList.ElementAt(position);
    personName.Text = person.Name;
    if(MainActivity.messages[person.Id].Count != 0)
        {
            personMessage.Text = MainActivity.messages[person.Id][MainActivity.messages[person.Id].Count - 1];
        }
    else
        {
            personMessage.Text = "";
        }
    personImage.SetImageResource(person.ImageId);
    return convertView;
}
}
}

У меня есть класс personAdapter, и в чате есть только listView. Так что я привязываю список к listView через адаптер. Я добавил человека вручную, чтобы увидеть меню чата. Если я добавлю изображения в папку для рисования, это не проблема. Но как мне добавить изображения для создания нового человека. Я не могу добавить изображения для рисования во время выполнения. Когда я пытаюсь прочитать изображения из внешнего хранилища. У них нет идентификатора ресурса. Таким образом, класс пользователя не принимает это.

{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
    public static List<Person> persons = new List<Person>();
    public static Dictionary<int, List<string>> messages = new Dictionary<int, List<string>>();
    PersonAdapter adapter;
    private static int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_main);
        persons.Add(new Person(0,"Safa", Resource.Drawable.person));
        persons.Add(new Person(1,"Melis", Resource.Drawable.person));
        persons.Add(new Person(2,"Orkun", Resource.Drawable.person));
        messages[0] = new List<string>();
        messages[1] = new List<string>();
        messages[2] = new List<string>();
        messages[0].Add("Naber?");
        messages[0].Add("Nasılsın?");
        messages[1].Add("Nerdesin?");
        messages[1].Add("Saat Kaç?");
        messages[2].Add("Buluşalım mı?");
        messages[2].Add("Kaçta?");
        ListView listView = (ListView)FindViewById(Resource.Id.listView);

        adapter = new PersonAdapter(this,persons);

        listView.Adapter = adapter;



        listView.ItemClick += (object sender, ItemClickEventArgs e) =>
        {
            Person person = persons[e.Position];
            var intent = new Intent(this, typeof(ChatActivity));
            intent.PutExtra("name", person.Name);
            intent.PutExtra("id", person.Id);
            this.StartActivity(intent);
        };



        FloatingActionButton fab = (FloatingActionButton)FindViewById(Resource.Id.fab);

        fab.Click += delegate
        {
            var intent = new Intent(this, typeof(AddContactActivity));
            this.StartActivity(intent);
        };

        if(Intent.GetStringExtra("person") != null)
        {
            Person newPerson = JsonConvert.DeserializeObject<Person>                                                 (Intent.GetStringExtra("person"));
            persons.Add(newPerson);
            messages.Add(newPerson.Id, new List<string>());
            adapter.NotifyDataSetChanged();
        }

    }
}
}

AddContactActivity:

public class AddContactActivity : Activity
{
    private ImageView imageView;
    private Button loadButton;
    private Button addButton;
    private EditText nameEditText, surnameEditText;
    private int index;
    private string filename;
    public static int SELECT_IMAGE = 1001;
    Drawable drawable;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_addContact);
        imageView = FindViewById<ImageView>(Resource.Id.load_image_imageView);
        loadButton = FindViewById<Button>(Resource.Id.load_image_button);
        addButton = FindViewById<Button>(Resource.Id.add_contact_button);
        nameEditText = FindViewById<EditText>(Resource.Id.name_editText);
        surnameEditText = FindViewById<EditText>(Resource.Id.surname_editText);
        loadButton.Click += loadButtonClicked;
        addButton.Click += addContactButtonClicked;

    }

    private void addContactButtonClicked(object sender, EventArgs e)
    {
        index = MainActivity.messages.Count;
        Console.WriteLine(index);
        Person newPerson = new Person(index, nameEditText.Text + " " + surnameEditText.Text, drawable.GetHashCode());
        Intent intent = new Intent(this, typeof(MainActivity));
        intent.PutExtra("person", JsonConvert.SerializeObject(newPerson));
        StartActivity(intent);
    }

    private void loadButtonClicked(object sender, EventArgs e)
    {
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
        {
        Intent = new Intent();
        Intent.SetType("image/*");
        Intent.SetAction(Intent.ActionGetContent);
        StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), SELECT_IMAGE);
        }
        else
        {
            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, 12);
        }
    }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if ((requestCode == SELECT_IMAGE) && (resultCode == Result.Ok) && (data != null))
        {
                Android.Net.Uri uri = data.Data;
                Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                imageView.SetImageBitmap(bitmap);
        }
        else
        {
            Toast.MakeText(this.ApplicationContext, "You haven't picked an image", ToastLength.Short).Show();
        }
    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
    {
        if (requestCode == 12)
        {
            if ((grantResults.Length == 1) && (grantResults[0] == Permission.Granted))
            {
                Intent = new Intent();
                Intent.SetType("image/*");
                Intent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), SELECT_IMAGE);
            }
        }
        else
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

1 Ответ

0 голосов
/ 05 марта 2020

Хотите ли вы достичь такого результата, как этот GIF?

enter image description here

Исходя из вашего кода, вам нужно несколько шагов для его достижения.

Прежде всего, мы должны использовать Преобразование битовой карты в строку Base64 для достижения этого, мы можем создать MyUtils.cs

        public class MyUtils
    {
        public static string ConvertBitMapToString(Bitmap bitmap)
        {

            byte[] bitmapData;
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 50, stream);
                bitmapData = stream.ToArray();
            }

            string ImageBase64 = Convert.ToBase64String(bitmapData);

            return ImageBase64;
        }

        public static Bitmap ConvertStringToBitmap(string mystr)
        {
            byte[] decodedString = Base64.Decode(mystr, Base64.Default);
            Bitmap decodedByte = BitmapFactory.DecodeByteArray(decodedString, 0, decodedString.Length);

            return decodedByte;
        }
    }

Затем мы должны изменить тип ImageId на string как следующий код.

    public string ImageId   // property
    {
        get { return imageId; }   // get method
        set { imageId = value; }  // set method
    }

Пожалуйста, измените настройку Image way в MainActiviy и Adapter.

Вот мое демо, вы можете скачать его и обратиться к нему.

https://github.com/851265601/TransferImageBtwActivities

...