我有一个关于做whatsapp克隆的作业。但是我有一个问题。我有一个添加联系人屏幕。用户从图库中选择图像,然后输入其名称。当他们单击添加按钮时,列表项将被添加到聊天活动中。屏幕截图如下。我有一个人类,如:
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。我手动添加了一些人以查看聊天菜单。如果我将图像添加到可绘制文件夹,则没有问题。但是我如何添加图像来创建新的人。我无法在运行时将图像添加到drawable。当我尝试从外部存储读取图像时。他们没有资源ID。因此,人类不接受。
{
[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);
}
}
您是否想获得像这样的GIF结果?
根据您的代码,需要执行一些服务器步骤才能实现它。
首先,我们应该使用将位图转换为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
}
这里是我的演示,您可以下载并参考它。