添加按钮,在ImageView的

问题描述:

在我的应用我有一个是毕加索填充于ImageView的:添加按钮,在ImageView的

Picasso.with(context).load("http://example.com/logo.png").into(imageView); 

这工作得很好。但是,我想在每个ImageView的顶部角落添加一个按钮。显然,这意味着要创建我自己的可重用实例。

我很困惑,最好的方法来处理它。理想情况下,我想创建一个ImageView的子类来保留上面的语法和语义。 (“这是一个ImageView 加上一点”)但是,制作这种结构所需的XML需要一个RelativeLayout或FrameLayout作为它的根,并且我不能将它指向ImageView子类。

我怎样才能有效地创建这样的子类?

+0

你想imageview是可点击或添加一个新的按钮吗? – 2014-10-22 06:20:08

+0

添加一个新按钮。 AOSP拨号程序的快速拨号“...”菜单提供了大致的想法。 – thirtythreeforty 2014-10-22 06:20:42

+0

顺便说一句,imageview也是可点击的,但我知道如何实现它。 – thirtythreeforty 2014-10-22 06:21:12

好吧,既然ImageView不是视图组,你不能在imageview的子类中添加一个按钮。

我会解决这个问题,而不是创建一个视图,这将是一个视图组前例的子类。帧/ Realtive /等-布局。

它将包含ImageView和Button以及方法 getImageView()。

然后你的毕加索电话会是: Picasso.with(context).load(“http://example.com/logo.png”).into(mCustomView.getImageView());

---编辑---

OK因为我对我的写作手机我不能举一个例子。 这会给你一个可重复使用的视图,也可以以编程方式充气。 您将不得不创建一个XML布局文件,以便通过您的自定义类来充气。

public class MyCustomImageView extends FrameLayout { 
    private ImageView mImageView; 
    private Button mButton; 
    private Context mContext; 

    public MyCustomImageView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     this.mContext = context; 
     LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View view = layoutInflater.inflate(R.layout.custom_imageview, this); 
     mImageView = (ImageView) view.findViewById(R.id.iv_imgv); 
     mButton = (Button) view.findViewById(R.id.b_btn); 

     //mImageView.setOnClickListener(new OnClickListener(){...}); 
     //mButton.setOnClickListener(new OnClickListener(){...}); 
    } 

    //Return image view for image loading etc. 
    public ImageView getImageView(){ 
     return this.mImageView; 
    } 

    //Add onClickListener for the button 
    public void setButtonOnClickListener(inListener){ 
     mButton.setOnClickListener(inListener); 
    } 

    //If you want you can simulate this to be an image view 
    // Ex.. 
    public void setImageDrawable(Drawable drawable){ 
     iv.setImageDrawable(drawable); 
    } 
} 

这可以从XML布局夸大;

<com.example.packagename.customview.MyCustomImageView ... /> 

或以编程方式;

MyCustomImageView customview = new MyCustomImageView(context); 
    custom.setImageDrawable(drawable); 
    custom.setButtonOnclickListener(new OnClickListener(){...});