[英]How to set image path on image view in android
我有以下代碼,我得到id,名稱和圖像路徑。
我想在圖像視圖中顯示該圖像路徑。
public class AllProductsActivity extends ListActivity {
String pid;
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "example.com/files/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_IMAGE1 = "image1";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", pid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET",
params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String image1 = c.getString(TAG_IMAGE1);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
map.put(TAG_IMAGE1, image1);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_row, new String[] { TAG_PID,
TAG_NAME, TAG_PRICE, TAG_IMAGE1 },
new int[] { R.id.pid, R.id.name, R.id.price,
R.id.thumbnail });
// updating Listview
setListAdapter(adapter);
}
});
}
}
}
我已經在列表適配器中傳遞image1
路徑,我已經在.xml文件中獲取了imageview。
但我沒有得到他們的螞蟻圖像。
list_row.xml containg image view:
<ImageView
android:id="@+id/thumbnail"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
如何在imageview中顯示圖像?
畢加索在另一個線程中下載圖像並為您管理:
這非常簡單,這是一個例子:
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder)
.resize(imgWidth, imgHeight)
.centerCrop()
.into(image);
您需要執行以下步驟:
1)您需要實現一個自定義適配器,它將根據該行上相應的URL延遲加載圖像來填充圖像
2)實現一個LazyLoader,可以在完成后下載圖像並刷新imageview
3)調用自定義適配器的getView方法時調用LazyLoading
4)在OnPostExecute中調用自定義適配器,而不是Listadapter
5)或者為了使LazyLoading部分更容易,您使用Universal Image Loader進行編碼
下載picasso jar文件並首先在android構建應用程序jar中添加:
現在只需從json獲取你的網址
if(response.login_data.avtar!= null && response.login_data.avtar.length()> 0){
String photo=response.login_data.avtar.toString();
infoLog("avatar"+photo);
String url=App.WEB_PHOTO_URL+photo;
infoLog("avatar url"+url);
Picasso.with(HealthProfile.this).load(url).into(img);
}
else {
Picasso.with(HealthProfile.this).load(R.drawable.user).into(img);
}
ImageView imageView=(ImageView)findViewById(R.id.animage);
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
String filePath = null;
filePath = imageUri.getPath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(filePath,options);
imageView.setImageBitmap(bitmap);
}
您可以簡單地使用Picasso lib,一個功能強大的Android圖像下載和緩存庫。
它提供了超級干凈的語法,因此您可以使用它而不會產生混淆。
例如,在您的適配器中,您嘗試這樣:
首先,如果您使用SimpleAdapter , ViewBinder就是您應該知道的。 詳情請參閱http://developer.android.com/reference/android/widget/SimpleAdapter.ViewBinder.html
然后,在你自己的ViewBinder的setViewValue,只需添加以下代碼:
Picasso.with(context).load(img_path).into(imgView)
或者,如果您自定義自己的適配器,請在覆蓋的getView函數中添加代碼。
最后,它會在您的圖像視圖中顯示圖像。
關於畢加索的更多細節: http : //square.github.io/picasso/
Universal Image Loader是您的另一種選擇,它也擁有眾多用戶。 它更具可定制性。 請參閱: https : //github.com/nostra13/Android-Universal-Image-Loader
太晚了但也許它可以幫助別人。
如果您可以在項目中使用某個圖像加載庫,只需使用此自定義圖像視圖以允許從xml設置URL。
由於您可以從xml設置url,因此可以直接將鏈接變量綁定到imageview。
創建自定義圖像視圖。
class MyImageView : ImageView {
var url: String = ""
set(value){
field = value
Glide.with(this).load(value).into(this)
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs : AttributeSet) : super(context,attrs){
val array = context.obtainStyledAttributes(attrs, R.styleable.MyImageView)
val url = array.getString(R.styleable.MyImageView_url)
if(url!=null){
Glide.with(this).load(url).into(this)
}
array.recycle()
}
constructor(context: Context, attrs: AttributeSet , defStyleAttr : Int) : super(context, attrs, defStyleAttr)
}
在attr.xml中添加它
<declare-styleable name="MyImageView">
<attr name="url" format="string" />
</declare-styleable>
在xml中使用它
<package.path.MyImageView
android:id="@+id/image_company_logo"
android:scaleType="fitCenter"
android:layout_width="match_parent"
android:layout_height="80dp"
android:contentDescription="logo"
app:url="@{invoice.invoiceLogoLink}"/> //for data binding purpose
在這里了解更多相關信息
您需要創建自定義適配器,擴充行布局並從布局中檢索ImageView。 然后,您可以通過編程方式設置ImageView,如:
File imgFile = new File(yourImagePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
yourImageView.setImageBitmap(myBitmap);
}
創建自己的適配器的教程: http : //www.vogella.com/tutorials/AndroidListView/article.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.