我的customView.onclick

时间:2015-11-19 05:46:05

标签: android onclicklistener android-custom-view

我搜索过但找不到我的问题的答案。

这就是我所拥有的:

private class BoxView extends View {
  private String caption;
  private OnClickListener bvClickListener = null
  public BoxView(Context context) {
    super(context);
    this.bvClickListener = new this.OnClickListener(){
  public void onClick (View v){
    /*v.setCaption("X"); view don't have this method */
      }}
  }

  public void setCaption(String s){
this.caption=s;
invalidate();
  } 
}

这就是我想要的:

private class BoxView extends View {
  private String caption;
  private OnClickListener bvClickListener = null
  public BoxView(Context context) {
    super(context);
    this.bvClickListener = new this.OnClickListener(){
  public void onClick (BoxView bv){
    bv.setCaption("X");
      }}
  }

  public void setCaption(String s){
this.caption=s;
invalidate();
  } 
}

我可能需要自定义视图的自定义方法。而且我希望能够在触发onclick时传递我的自定义视图而不是查看它的版本,以便我可以直接访问它。

更新

我希望能够访问真实对象而不是转换对象。所以我想避免这个:

public void onClick (View v){
 ((BoxView)v).setCaption("X");  
}

2 个答案:

答案 0 :(得分:1)

public class LongPressGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public void onLongPress(MotionEvent e) { super.onLongPress(e); // e will give you the location and everything else you want // This is where you will be doing whatever you want to. int eIndex = MotionEventCompat.getActionIndex(e); float eX = MotionEventCompat.getX(e, eIndex); float eY = MotionEventCompat.getY(e, eIndex); Log.d("X:Y = " + eX + " : " + eY); } @Override public boolean onDown(MotionEvent e) { return true; } }

中的方式调用setCaption方法
onClick

答案 1 :(得分:0)

Try this

class Main extents Activity
{
 BoxView boxView;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 // if view is used using layout then
boxView = (BoxView)findViewByID(id);

//else if directly used

 boxView = new BoxView(this);

 box.setOnClickListener(new onClickListener()
 {

 @Override
        public void onClick(View view) {
       boxView.setCaption("X");
boxView.invalidate();
        }
 });
    }

}