我是Android开发中的新手,我希望在从第一个Asynctask获取图像URL后加载图像。当我们点击按钮时,我看到了一个加载图像的教程,我想在活动开始后替换图像。 这是我的主要活动
package kori.dev.kori.activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import kori.dev.kori.R;
import kori.dev.kori.adapters.CardAdapter;
import kori.dev.kori.model.Card;
import kori.dev.kori.model.Carte;
/**
* Created by Thefractus Bombatus on 13/12/2016.
*/
public class MainCard extends AppCompatActivity implements LoadImageTask.Listener{
private RecyclerView recyclerView;
private CardAdapter adapter;
private List<Card> cardList;
public static Carte[] carte;
private ProgressDialog progressDialog ;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
loadtask();
super.onCreate(savedInstanceState);
setContentView(R.layout.main_card);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView sub_title = (TextView) findViewById(R.id.sub_title);
String title_sub = getIntent().getStringExtra("name_cat") ;
sub_title.setText(title_sub);
mImageView = (ImageView) findViewById(R.id.test_img);
Button btn_test = (Button) findViewById(R.id.btn_test);
btn_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("ooo",carte[0].getPhoto() );
new LoadImageTask(MainCard.this).execute(carte[0].getPhoto());
}
});
}
public void onImageLoaded(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
public void onError() {
Toast.makeText(this, "Error Loading Image !", Toast.LENGTH_SHORT).show();
}
/**
* Initializing collapsing toolbar
* Will show and hide the toolbar title on scroll
*/
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle("dride");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
}
private void loadscren(Carte[] cartes){
initCollapsingToolbar();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
cardList = new ArrayList<>();
adapter = new CardAdapter(this, cardList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
try {
Glide.with(this).load(R.drawable.carte_sport).into((ImageView) findViewById(R.id.backdrop));
} catch (Exception e) {
e.printStackTrace();
}
loadalbum(cartes);
}
private void loadalbum(Carte[] cartes){
int[] covers = new int[]{
R.drawable.album1,
R.drawable.album2,
R.drawable.album3,
R.drawable.album4,
R.drawable.album5,
R.drawable.album6,
R.drawable.album7,
R.drawable.album8,
R.drawable.album9,
R.drawable.album10,
R.drawable.album11};
int i = 0;
for(Carte c :cartes){
Card a = new Card(c.getCarte(), c.getVendeur(), covers[i]);
cardList.add(a);
i++;
}
adapter.notifyDataSetChanged();
}
/**
* Adding few albums for testing
*/
private void loadtask() {
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
new HttpRequestTaskCarte().execute();;
}
}, 3000);
}
/**
* RecyclerView item decoration - give equal margin around grid item
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
/**
* Converting dp to pixel
*/
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public class HttpRequestTaskCarte extends AsyncTask<Void,Void,Carte[]> {
@Override
protected Carte[] doInBackground(Void... params) {
try {
final String url = "http://ayelive.xyz/website/testRest/RestController.php?carte=shopping";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Carte[] greeting = restTemplate.getForObject(url, Carte[].class);
return greeting;
} catch (Exception e) {
Toast.makeText(MainCard.this, "Error Loading !", Toast.LENGTH_SHORT).show();
//Log.e("MainActivity", e.getMessage(), e);
}
return null;
}
protected void onPreExecute(){
progressDialog = new ProgressDialog(MainCard.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("chargement des elements...");
progressDialog.show();
}
@Override
protected void onPostExecute(Carte[] greeting) {
Carte[] greet =greeting;
carte = greet ;
Log.d("carte",greet[0].getPhoto());
Log.d("carte",greet[1].getCarte());
loadscren(greet);
progressDialog.dismiss();
}
}
}
图片任务加载
package kori.dev.kori.activity;
/**
* Created by THEOPHRACTUS on 23/12/2016.
*/
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
public LoadImageTask(Listener listener) {
mListener = listener;
}
public interface Listener{
void onImageLoaded(Bitmap bitmap);
void onError();
}
private Listener mListener;
@Override
protected Bitmap doInBackground(String... args) {
try {
//Log.d("cat",args[0]);
return BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
mListener.onImageLoaded(bitmap);
} else {
mListener.onError();
}
}
}
和适配器
package kori.dev.kori.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.List;
import kori.dev.kori.R;
import kori.dev.kori.activity.DetailActivity;
import kori.dev.kori.model.Card;
/**
* Created by Thefractus Bombatus on 13/12/2016.
*/
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.MyViewHolder> {
private Context mContext;
private List<Card> cardList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, count;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
count = (TextView) view.findViewById(R.id.count);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
public CardAdapter(Context mContext, List<Card> cardList) {
this.mContext = mContext;
this.cardList = cardList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.categorie_card, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
Card card = cardList.get(position);
holder.title.setText(card.getCatName());
holder.count.setText(card.getEntrName() );
// loading album cover using Glide library
Glide.with(mContext).load(card.getThumbnail()).into(holder.thumbnail);
holder.overflow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPopupMenu(holder.overflow);
}
});
}
/**
* Showing popup menu when tapping on 3 dots
*/
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_categorie, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
/**
* Click listener for popup menu items
*/
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_add_favourite:
Toast.makeText(mContext, "Ajouter au panier", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_play_next:
Intent intent = new Intent(mContext, DetailActivity.class);
mContext.startActivity(intent);
return true;
default:
}
return false;
}
}
@Override
public int getItemCount() {
return cardList.size();
}
}
PS:对不起我的英语:)
答案 0 :(得分:3)
答案 1 :(得分:1)
删除您的LoadImageTask
并使用适用于Android的几种高质量图片加载库之一。
我的建议是使用毕加索(http://square.github.io/picasso/),但还有其他如凌空影像装载,滑翔和壁画。
在build.gradle文件
上将库添加到项目中compile 'com.squareup.picasso:picasso:2.5.2'
然后在你的MainCard上你这样写:
btn_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("ooo",carte[0].getPhoto());
Picasso
.with(view.getContext())
.load(carte[0].getPhoto())
.into(mImageView);
}
});