我想提出一個聊天應用程序。 我有一個imageview的用戶配置文件。如何轉換字符串「A」到圖像中的Android?
如果用戶圖像爲空/空,我想顯示用戶名的第一個字母,例如:假設用戶名是「UNKNOWN」,所以我只想在該圖像視圖上顯示U.
Click here to see sample of what I want
我曾嘗試:
首先我檢查,如果用戶圖像爲null
if (item.getSender_img_url() == null || item.getSender_img_url().isEmpty()||item.getSender_img_url().equals("null")) {
System.out.println(TAG + " photo is not available ");
//here i am getting first alphabet of Users Name
String[] result = item.getSenderName().split("\\s+");
// This is a regex for matching spaces
// The string we'll create
String abbrev = "";
// Loop over the results from the string splitting
for (int i = 0; i < result.length; i++) {
System.out.println(TAG + " abbrev 1 "+ abbrev);
// Grab the first character of this entry
char c = result[i].charAt(0);
System.out.println(TAG + " abbrev c "+ c);
// If its a number, add the whole number
if (c >= '0' && c <= '9') {
abbrev += result[i];
}
// If its not a number, just append the character
else {
abbrev += c;
}
System.out.println(TAG + " abbrev 3 "+ abbrev);
}
//here i am converting string value into image
Bitmap bm = StringToBitMap(abbrev.toString());
//here i am setting covertes bitmat image into image view
((ViewHolder) holder).friends_image.setImageBitmap(bm);
} else {
System.out.println(TAG + " photo is available ");
try {
Picasso.with(mContext).load(item.getSender_img_url())
.error(R.drawable.profile_avatar)
.placeholder(R.drawable.profile_avatar).resize(40, 40).centerCrop()
.into(((ViewHolder) holder).friends_image);
} catch (Exception e) {
e.printStackTrace();
}
}
.................................
/**
* @param encodedString
* @return bitmap (from given string)
*/
public static Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
任何幫助嗎?
只需要26個不同的預先構建的圖像並選擇所需的圖像可能會更容易,而不是試圖動態創建一個。 – Neil