将图像位图设置为imageView适配器

时间:2017-06-12 18:27:30

标签: java android android-layout bitmap android-recyclerview

目前我正在使用自定义适配器/循环视图在图像下构建一个简单的图像和一个小画廊,每当我点击下面的一个图像时,它会在上面的主imageView中加载图像。

我现在的问题是,每当我点击galery上的图像我都会请求图片时,我会获得点击图片的ID并再次加载图片以显示在上面。

我不太喜欢我的解决方案,我想获取点击图片的位图并将其显示在上面的imageView中。

因此,在我的主要活动中,我做了一个简单的请求来获取主图像,其余的图像正在加载我的活动的另一个请求,该请求加载了包含所有图像的回收视图。

这是活动:

public class PhotosForPlant extends AppCompatActivity implements IResult,PhotosForPlantsAdapter.OnItemClickListener  {

    RecyclerView recyclerView;
    ArrayList<Photo> photos = new ArrayList<Photo>();

    VolleyService mVolleyService;
    IResult mResultCallback = null;
    IResult mResultCallback2 = null;
    final String GETREQUEST = "GETCALL";
    PhotosForPlantsAdapter adapter;
    String token;

    TextView familyTxt;
    TextView genreTxt;
    TextView specieTxt;
    TextView specieDescription;
    ImageView plantImg;


    int familyId;
    int genreId;
    String familyName;
    String genreName;



    Double lat = null;
    Double lon = null;
    Double alt = null;

    String time = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.AppTheme);
        setContentView(R.layout.photos_for_plant);

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);;
        setSupportActionBar(myToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        findViewById(R.id.user_ic2).setVisibility(View.GONE);

        TextView toolbarText = (TextView) myToolbar.findViewById(R.id.toolbar_title);
        toolbarText.setText("Dados planta");;

        familyTxt = (TextView)findViewById(R.id.FamilyName);
        genreTxt = (TextView)findViewById(R.id.GenreName);
        specieTxt = (TextView)findViewById(R.id.SpecieName);
        specieDescription = (TextView)findViewById(R.id.specieDescription);
        plantImg = (ImageView)findViewById(R.id.plantImage);

        token = checkForToken();

        getAllPhotos();
        getSpecificPlant();
    }

    private void getSpecificPlant() {

        String id = getIntent().getExtras().getString("plantId");

        final String URL = "http://109d0157.ngrok.io/plants/" + id;

        getSpecificVolleyCallback();

        mVolleyService = new VolleyService(mResultCallback2,this);

        mVolleyService.getDataObjectVolley(GETREQUEST,URL,token);
    }


    private void getAllPhotos() {

        String id = getIntent().getExtras().getString("plantId");

        final String URL = "http://109d0157.ngrok.io/fotos/" + id + "/plants";

        getFotosForPlantVolleyCallback();

        mVolleyService = new VolleyService(mResultCallback,this);

        mVolleyService.getDataVolley(GETREQUEST,URL,token);

        recyclerView = (RecyclerView)findViewById(R.id.gallery);
        recyclerView.setHasFixedSize(true);

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5,GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new PhotosForPlantsAdapter(getApplicationContext(), photos,this);
        recyclerView.setAdapter(adapter);
    }

    private void getSpecificVolleyCallback() {
        mResultCallback2 = new IResult() {
            @Override
            public void notifySuccess(String requestType, JSONObject response) {
                try {
                    Log.d("ENTREIAQUI","ENTREI");
                    String specie = response.getString("specie");
                    loadImage(specie);
                    familyName = response.getJSONObject("genre").getJSONObject("family").getString("name");
                    genreName = response.getJSONObject("genre").getString("name");
                    genreId = response.getJSONObject("genre").getInt("id");
                    genreTxt.setText(genreName);
                    specieTxt.setText(specie);
                    familyTxt.setText(familyName);
                    specieDescription.setText(response.getString("description"));
                    familyId = response.getJSONObject("genre").getJSONObject("family").getInt("id");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                Log.d("ENTREIAQUI","ENTREI");
            }

            @Override
            public void notifyError(String requestType, VolleyError error) {
                Log.d("erro!",error.toString());
                Log.d("ENTREIAQUI","ENTREI");

            }
        };
    }

    void getFotosForPlantVolleyCallback(){
        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType, JSONObject response) {
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                Photo photo;
                // iterate over the JSONArray response
                for (int i=0; i < response.length(); i++) {
                    try {
                        JSONObject object = response.getJSONObject(i); // get the individual object from JSONArray
                        Log.d("objeto",object.toString());
                        int id = Integer.parseInt(object.getString("id")); // get the unique identifier from the object
                        if(lat != null && lon != null && alt != null){
                            lat = Double.parseDouble(object.getString("lat"));
                            lon = Double.parseDouble(object.getString("lon"));
                            alt = Double.parseDouble(object.getString("altitude"));
                        }
                        time = object.getString("date");
                        String path = object.getString("image");
                        photo = new Photo(path,id,lat,lon,alt,time); // construct the object
                        photos.add(photo); // add the object to the arraylist so it can be used on the cardLayout


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void notifyError(String requestType, VolleyError error) {
                Log.d("resposta",error.toString());
            }
        };
    }

    public void genrePressed(View view){
        Intent i = new Intent(this,SpecieLibrary.class);
        i.putExtra("id",String.valueOf(genreId));
        i.putExtra("name",String.valueOf(genreName));
        startActivity(i);
    }

    public void familyPressed(View view){
        Intent i = new Intent(this,GenreLibrary.class);
        i.putExtra("id",String.valueOf(familyId));
        i.putExtra("name",String.valueOf(familyName));
        startActivity(i);
    }

    @Override
    public void notifySuccess(String requestType, JSONObject response) {

    }

    @Override
    public void notifySuccess(String requestType, JSONArray response) {

    }

    @Override
    public void notifyError(String requestType, VolleyError error) {

    }

    public String checkForToken() {
        SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
        String tokenKey = getResources().getString(R.string.token);
        String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
        return token;
    }

    public void loadImage(String specie){
        String url = "http://109d0157.ngrok.io/images/" + specie + "/Thumbnail.jpg";
        Picasso.with(PhotosForPlant.this)
                .load(url)
                .into(plantImg);
    }

    @Override
    public void onRowClick(int position, int id,String path, View view) {
        String url = "http://109d0157.ngrok.io/" + path;

        Picasso.with(PhotosForPlant.this)
                .load(url)
                .into(plantImg);
    }
}

loadImage,我加载主图像,然后我有来自我的自定义适配器的onRowClick,我得到了点击行的路径,所以我再次加载它,但我需要的是以某种方式那里的位图和plantImg上的setImageResource。

这是我的适配器:

public class PhotosForPlantsAdapter extends RecyclerView.Adapter<PhotosForPlantsAdapter.ViewHolder>  {
    private ArrayList<Photo> photos;
    private Context context;


    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onRowClick(int position,int id,String path, View view);

    }

    public PhotosForPlantsAdapter(Context context, ArrayList<Photo> photos,OnItemClickListener listener) {
        this.photos = photos;
        this.context = context;
        this.listener = listener;
    }

    @Override
    public PhotosForPlantsAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.photos_for_plant_row, viewGroup, false);
        return new ViewHolder(view);
    }


    @Override
    public void onBindViewHolder(final PhotosForPlantsAdapter.ViewHolder viewHolder, final int i) {

        String urlFoto = photos.get(i).getPath();
        String url = "http://109d0157.ngrok.io/" + urlFoto;

        viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);

        Picasso.with(context)
                .load(url)
                .resize(240, 120)
                .centerInside()
                .into(viewHolder.img);

        viewHolder.img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onRowClick(viewHolder.getAdapterPosition(),photos.get(i).getId(),photos.get(i).getPath(), view);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return photos.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private ImageView img;
        public ViewHolder(View view) {
            super(view);
            img = (ImageView) view.findViewById(R.id.img);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试以这种方式将Image设置为位图

URL newurl = new URL("http://109d0157.ngrok.io/" + urlFoto); 
mIcon_val=BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); 
viewHolder.img.setImageBitmap(mIcon_val);

以这种方式获取图像

Bitmap imgBitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();