如何将图像URL从活动传递到警报对话框作为imageview?

时间:2016-05-10 11:40:44

标签: android json listview android-intent android-alertdialog

这是我的CartRowHolder

class CartRowHolder {
  ImageView icon;
  TextView txtprice,txttitle,personalize;
  TextView txtquantity;
  ImageView imgdelete,imgedit,image;
  public CartRowHolder(View v) {
    icon=(ImageView)v.findViewById(R.id.imageicon);
    txtprice=(TextView)v.findViewById(R.id.txtoprice);
    txttitle=(TextView)v.findViewById(R.id.txtotitle);
    txtquantity=(TextView)v.findViewById(R.id.txtoquantity);
    personalize=(TextView)v.findViewById(R.id.txtpersonalize);
    imgdelete=(ImageView)v.findViewById(R.id.imgdelete);
    imgedit=(ImageView)v.findViewById(R.id.edit);
  }
}

现在在ListView a ImageView和删除按钮,编辑按钮就在那里当我点击编辑对话框打开时,在对话框中我想传递imageView .... 。我有ImageUrl

class CartAdapter extends BaseAdapter {
  Activity activity;
  List<CartItem> cartItemList;
  ImageLoader imageLoader;
  LayoutInflater layoutInflater;
  CartItem cartItem;
  AppPreferenceManager appPreferenceManager;

  public CartAdapter(Activity activity,List<CartItem>cartItemList) {
    this.activity=activity;
    this.cartItemList=cartItemList;
    appPreferenceManager=new AppPreferenceManager(activity);
  }

  public int getCount() {
    return cartItemList.size();
  }

  @Override
  public Object getItem(int position) {
    return cartItemList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
    cartItem=cartItemList.get(position);
    CartRowHolder cartRowHolder;
    Bundle extras = getIntent().getExtras();
    TextView tk;

    if (extras != null) {

    }

    if(imageLoader==null) {
      imageLoader=new ImageLoader(activity);
    }
    if(layoutInflater==null) {
      layoutInflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    if(convertView==null) {
      convertView=layoutInflater.inflate(R.layout.order_row,null);
      cartRowHolder=new CartRowHolder(convertView);
      cartRowHolder.imgdelete.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
          CartItem cartItem=cartItemList.get(position);
          deletCartItem(cartItem.getPid());
        }
      });
      cartRowHolder.imgedit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {                     
          final CartItem cartItem=cartItemList.get(position);
          ImageView image;
          final EditText personalise;
          Button update;
          final TextView quan,title1;

          final ImageButton plusd,minusd;
          final AlertDialog alertDialog;
          View view=getLayoutInflater().inflate(R.layout.activity_edit,null);
          final AlertDialog.Builder builder=new AlertDialog.Builder(CartActivity.this).setView(view);
          update = (Button)view.findViewById(R.id.update);
          quan=(TextView)view.findViewById(R.id.quan);
          minusd=(ImageButton)view.findViewById(R.id.minus);
          plusd=(ImageButton)view.findViewById(R.id.plus);
          alertDialog=builder.create();
          title1=(TextView)view.findViewById(R.id.TitleView);
          title1.setText(cartItemList.get(position).getName());
          personalise=(EditText)view.findViewById(R.id.editpersonalize);
          personalise.setText(cartItemList.get(position).getPersonalize());
          quan.setText(cartItemList.get(position).getQunatity());
          image=(ImageView)view.findViewById(R.id.image1);
          //imageLoader.DisplayImage(Bitmap.get);
          final int num=Integer.parseInt(quan.getText().toString());
          final int[] counter = {num};

          plusd.setOnClickListener(new View.OnClickListener() {
            //int counter=0;
            @Override
            public void onClick(View v) {
              //Toast.makeText(CartActivity.this, "Positive is click", Toast.LENGTH_SHORT).show();

              counter[0]++;
              quan.setText(""+ counter[0]);
              minusd.setClickable(true);
              plusd.setClickable(true);
              if(counter[0] ==10){
                plusd.setClickable(false);
                minusd.setClickable(true);
                Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
              }
              //Toast.makeText(SingleItem_Activity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
              if(counter[0] >=10) {
                plusd.setClickable(false);
                minusd.setClickable(true);
                Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
              }
            }
          });
          minusd.setOnClickListener(new View.OnClickListener() {
            // int counter=0;
            @Override
            public void onClick(View v) {
              if(counter[0] ==1) {
                minusd.setClickable(false);
              }
              else{
                counter[0] = counter[0] -1;
                quan.setText(""+ counter[0]);
                if(counter[0] <=1){
                  minusd.setClickable(false);
                  plusd.setClickable(true);}
                }
              }
            });
            update.setOnClickListener(new View.OnClickListener() {
              @Override
               public void onClick(View v) {
                 String update_quan=quan.getText().toString();
                 String update_personalise = personalise.getText().toString();
                 updateCartItem(update_quan,cartItem.getPid(),update_personalise);
                 //Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
                 alertDialog.dismiss();
               }
           });
        alertDialog.show();
      }
    });

    cartRowHolder.txttitle.setText(cartItem.getName());
    cartRowHolder.txtprice.setText(cartItem.getSubtotal());
    cartRowHolder.txtquantity.setText(cartItem.getQunatity());
    cartRowHolder.personalize.setText(cartItem.getPersonalize());
    imageLoader.DisplayImage(cartItem.getImage(), cartRowHolder.icon);
  }
  return convertView;
}

2 个答案:

答案 0 :(得分:0)

好的,你需要遵循以下代码: 1)在清单中添加互联网权限

<uses-permission android:name="android.permission.INTERNET" />

2)您需要更新列表适配器

private static final int MIN_RECORDS_NUMBER = 11;

private Context         _con;
private List<Person>    _data;

public PersonAdapter(Context context, List<Person> data)
{
    _con = context;
    _data = data;
}

@Override
public int getCount()
{
    return _data.size();
}

@Override
public Person getItem(int position)
{
    return _data.get(position);
}

@Override
public long getItemId(int position)
{
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
    Holder h = null;
    if (convertView == null)
    {
        h = new Holder();
        convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);

        h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
        h._fName = (TextView) convertView.findViewById(R.id.f_name);
        h._lName = (TextView) convertView.findViewById(R.id.l_name);
        h._age = (TextView) convertView.findViewById(R.id.age);
        h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
        convertView.setTag(h);
    }
    else
    {
        h = (Holder) convertView.getTag();
    }

        final Person p = getItem(position);
        h._fName.setText(p._fName);
        h._lName.setText(p._lName);
        h._age.setText(String.valueOf(p._age));
        h._backgroundItem.setActivated(p._selected);
        h._editBtn.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                ((MainActivity)_con).onEditClick(p._url);
            }
        });


    convertView.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            Person p = getItem(position);
            Intent i = new Intent(_con,SecondActivity.class);
            i.putExtra("DATA", p._fName);
            _con.startActivity(i);
        }
    });


    return convertView;

}


public void setData(List<Person> data)
{
    _data = data;
    notifyDataSetChanged();

}

private static class Holder
{
    public LinearLayout _backgroundItem;
    public TextView     _fName;
    public TextView     _lName;
    public TextView     _age;
    public Button       _editBtn;
}

public interface IDialog
{
    public void onEditClick(String url);
}

3)更新您的主要活动

public class MainActivity extends Activity implements IDialog

{

private ListView        _listView;
private PersonAdapter   _adapter;
private Button          _sortBtn;
private List<Person>    _data;
private int             _sort;
private int             _selectedItemIndex;
private Bitmap          _bit;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    _listView = (ListView) findViewById(R.id.list);
    _sortBtn = (Button) findViewById(R.id.sort_list_btn);
    _selectedItemIndex = -1;
    _sort = 1;
    _data = new ArrayList<Person>();
    _data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
    _data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
    _data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
    _data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
    _data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
    _data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));

    _adapter = new PersonAdapter(this, _data);
    _listView.setAdapter(_adapter);


    _listView.setOnItemClickListener(new OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            if(position<_data.size())
            {
                if(_selectedItemIndex>-1)
                {
                    _data.get(_selectedItemIndex)._selected = false;
                }
                _selectedItemIndex = position;

                _data.get(position)._selected = true;
                _adapter.setData(_data);
            }
        }
    });

    _sortBtn.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {


            if(_selectedItemIndex>-1)
            {
                _listView.clearChoices();
                String fName = _adapter.getItem(_selectedItemIndex)._fName;

                Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
                Collections.sort(_data, sortById);

                int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
                _selectedItemIndex = newSelectedItemIndex;


                _adapter.setData(_data);

                if(newSelectedItemIndex>-1)
                {
                    _listView.setItemChecked(newSelectedItemIndex, true);
                }

                _sort = -_sort;
            }
            else
            {
                Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
                Collections.sort(_data, sortById);

                _adapter.setData(_data);
                _sort = -_sort;
            }
        }


    });

}

private int getSelectedItemIndexByFName(String name)
{
    for(int index=0;index<_data.size();index++)
    {
        if(_data.get(index)._fName.equals(name))
        {
            return index;
        }
    }
    return -1;
}

public static class Person
{
    public String   _url;
    public String   _fName;
    public String   _lName;
    public int      _age;
    public boolean  _selected;

    public Person(String url,String fName, String lName, int age)
    {
        _url = url;
        _fName = fName;
        _lName = lName;
        _age = age;
    }

    public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
    {
        return new Comparator<Person>()
        {
            @Override
            public int compare(Person patient1, Person patient2)
            {
                return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
            }
        };
    }

}

public Bitmap getBitmapFromURL(String src) {
    try
    {
        URL url = new URL(src);
        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
        httpCon.setInstanceFollowRedirects(true);
        Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
        return image;
    }
    catch (MalformedURLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}


@Override
public void onEditClick(final String url)
{
    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            _bit = getBitmapFromURL(url);
            runOnUiThread(new Runnable()
            {

                @Override
                public void run()
                {


                     Dialog dialog = new Dialog(MainActivity.this);
                        dialog.setContentView(R.layout.custom_image);

                        ImageView image = (ImageView) dialog.findViewById(R.id.image);
                        if(_bit!=null)
                         {
                             image.setImageBitmap(_bit);
                         }
                        dialog.setTitle("This is my custom dialog box");
                        dialog.setCancelable(true);
                        //there are a lot of settings, for dialog, check them all out!

                        dialog.show();
                }
            });
        }
    }).start();



}

4)自定义图像布局

   <?xml version="1.0" encoding="utf-8"?>
<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/image"/>

</LinearLayout>

一点解释: 活动和列表适配器之间有一个接口(IDialog) 作为数据的一部分,每个项目(人)都有一个字段URL,当用户点击按钮时,界面“通知”活动并下载相应的图像并在对话框中显示

答案 1 :(得分:-1)

经过这么一个小时后,我发现了Soloution。现在在对话框中我可以再次下载图像.....

                   imageFileURL="url";
                    String imageFileURL=cartItemList.get(position).getImage();
                    try {
                        URL url = new URL(imageFileURL);
                        URLConnection conn = url.openConnection();
                        HttpURLConnection httpConn = (HttpURLConnection)conn;
                        httpConn.connect();
                            InputStream inputStream = httpConn.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                            inputStream.close();
                            image.setImageBitmap(bitmap);

                    } catch (MalformedURLException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }