簡體   English   中英

將圖像位圖設置為imageView適配器

[英]set image bitmap to imageView adapter

目前,我正在使用自定義適配器/回收視圖在該圖像下構建一個簡單的圖像和一個小畫廊,每次當我單擊下面的圖像之一時,它將圖像加載到上面的主imageView中。

目前,我的問題是,每次我在圖庫上單擊圖像時,我都會請求圖像,然后獲取所單擊圖像的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);
        }
    }
}

嘗試以這種方式將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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM