如何从Rest API将图像资源设置为Android ImageView

时间:2016-04-04 07:44:40

标签: android rest android-layout gridview

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.*******.******.app.R;
import com.*******.******.app.adapter.CustomAdapter;
import com.*******.******.app.adapter.CustomPromoAdapter;
import com.*******.******.app.pojo.Campaigns;
import com.*******.******.app.pojo.ConsumerProfile;

import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;

public class Promo extends AppCompatActivity {
    private ArrayList<String> imageurls = new ArrayList<>();
    private ArrayList<String> imgnames = new ArrayList<>();
    GridView gridview;
    Context context;
    ArrayList programName;
    String campid,campImage,campName;
    TextView name;
    ImageView images;
  //  public static String[] programNameList = {"AppleMacBook", "HP_note_Book", "LG_NEXUS", "NokiaLumia", "SamsungRT", "SONY_BRAVIA", "Sansui"};
  //  public static int[] programImages = {R.drawable.apple, R.drawable.hp, R.drawable.nexus, R.drawable.lumia, R.drawable.fridge, R.drawable.tv, R.drawable.tv1};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_promo);
        new HttpRequesrPromo().execute();
        new HttpLocationPromo().execute();
        gridview = (GridView) findViewById(R.id.gridView1);
        //gv.setAdapter(new CustomPromoAdapter(this,programNameList,programImages));
        CustomPromoAdapter adapter = new CustomPromoAdapter(this,imageurls,imgnames);
        gridview.setAdapter(adapter);
        name = (TextView) findViewById(R.id.textView1);
        images = (ImageView) findViewById(R.id.imageView1);

    }

    private class HttpRequesrPromo extends AsyncTask<Void, Void, Campaigns> {

        @Override
        protected Campaigns doInBackground(Void... params) {

            try {

                final String url = "http://myurl";


                RestTemplate restTemplate = new RestTemplate();
                Campaigns campa = restTemplate.getForObject(url, Campaigns.class);
                return campa;

            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);

            }
            return null;
        }

        @Override
        protected void onPostExecute(Campaigns campa) {
            super.onPostExecute(campa);
            campid = campa.getId();
            Log.d("Campaign Idddddd~~~~~~~~", "onPostExecute: " + campid);

        }
    }

    private class HttpLocationPromo extends AsyncTask<Void, Void, Campaigns> {

        @Override
        protected Campaigns doInBackground(Void... params) {
            try {

                final String url = "http://myurl";


                RestTemplate restTemplate = new RestTemplate();
                Campaigns locationcampa = restTemplate.getForObject(url, Campaigns.class);
                return locationcampa;

            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);

            }
            return null;
        }

        @Override
        protected void onPostExecute(Campaigns locationcampa) {
            super.onPostExecute(locationcampa);
            campImage=locationcampa.getImage();
            campName=locationcampa.getName();
            imgnames.add(campName);
            name.setText(campName);

            Log.d("ImageUUURRRLLL", "onPostExecute: " + campImage);
            Log.d("CampNNNAAMMEEE", "onPostExecute: " +campName);
            imageurls.add(campImage);



        }
    }
}
  1. 这是我在此活动我从静止服务中获取图像并将其添加到列表中。
  2. 我有一个带有CustomAdapter ImageView和TextView的GridView我想将图像资源设置为图像视图。
  3. 下面是我的适配器.......
  4. import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.app.R;
    import com.app.activity.MainActivity;
    import com.app.activity.Promo;
    
    import java.util.ArrayList;
    
    /**
     * Created by ns2 on 2/4/16.
     */
    public class CustomPromoAdapter extends BaseAdapter{
        ImageView imageView;
        TextView textView;
        String [] result;
        Context context;
        int [] imageId;
        private static LayoutInflater inflater=null;
        public CustomPromoAdapter(Promo promo, ArrayList<String> imageurls, ArrayList<String> imgnames) {
            // TODO Auto-generated constructor stub
            //result=programNameList;
          //  context=promo;
          //  imageId=programImages;
            inflater = ( LayoutInflater )context.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
        }
    
        @Override
        public int getCount() {
            return result.length;
        }
    
        @Override
        public Object getItem(int position) {
            return position;
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view;
            view=inflater.inflate(R.layout.promo_gridlist,null);
           /* textView=(TextView)view.findViewById(R.id.textView1);
            imageView=(ImageView)view.findViewById(R.id.imageView1);
            imageView.setImageResource(imageId[position]);
            textView.setText(imageId[position]);*/
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
                }
            });
            return view;
        }
    }
    
    1. 这是我的适配器。
    2. &#13;
      &#13;
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
      
          android:orientation="vertical" >
      
          <ImageView
              android:id="@+id/imageView1"
              android:layout_gravity="center"
              android:layout_width="88dp"
              android:layout_height="88dp"
              android:layout_marginTop="5dp"
              android:layout_marginBottom="5dp"
              />
      
          <TextView
              android:id="@+id/textView1"
              android:layout_gravity="center"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textSize="15dp"
              android:layout_marginTop="5dp"
              android:layout_marginBottom="5dp"
              android:text="TextView" />
      
      </LinearLayout> 
      &#13;
      &#13;
      &#13;

      1. 这是我使用ImageView和TextView的布局。
      2. &#13;
        &#13;
        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
        
            tools:context=".activity.Promo" >
        
            <GridView
                android:id="@+id/gridView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/textView1"
                android:numColumns="2" >
        
            </GridView>
        
        
        
        </RelativeLayout>
        &#13;
        &#13;
        &#13;

        1. 这是我的主要布局。
        2. 我现在有一个列表中的图片网址我想将这些网址设置为ImageView。
        3. 我是Android的新手可以帮助我如何解决这个问题。
        4. 感谢他们........

3 个答案:

答案 0 :(得分:0)

实现这一目标的最佳方法是使用毕加索库。

Picasso.with(上下文)     .load(URL)     .placeholder(R.drawable.user_placeholder)     .error(R.drawable.user_placeholder_error)     .into(ImageView的);

了解更多详情

答案 1 :(得分:0)

试试这个,

URL photoUrl = new URL(imageUrl);
mIcon = BitmapFactory.decodeStream(photoUrl.openConnection() .getInputStream());

imageView.setImageBitmap(mIcon);

答案 2 :(得分:0)

从服务器加载图像的最佳方法是

Glide.with(mContext)
        .load(imageUrl)
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .placeholder(R.drawable.default)
        .error(R.drawable.default)
        .override(400, 400)
        .centerCrop()
        .into(imageView);

如需更多信息,请点击此处: https://github.com/bumptech/glide