我需要滚动自定义视图。为了达到这个目的,我在XML布局中做了一个scrollview,并添加了Relativelayout作为其唯一的孩子。然后在运行时,我在RelativeLayout中添加自定义视图。
CustomView类代码如下:为onClick监听器设置动态添加的自定义视图
public class CustomView extends View {
int bgColor ;
Point x ;
Point y ;
Point z ;
int itemHeight;
String tag;
public CustomView(Context context) {
super(context);
}
public void setParameters (int bgColor , Point a , Point b , Point c, int itemHeight , String text)
{
this.bgColor = bgColor;
this.x = a;
this.y = b;
this.z = c;
this.itemHeight = itemHeight;
this.tag = text;
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStrokeWidth(4);
paint.setColor(bgColor);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
Point a = new Point(x.x, x.y);
Point b = new Point(y.x, y.y);
Point c = new Point(z.x, z.y);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(x.x,x.y);
path.lineTo(b.x, b.y);
path.lineTo(c.x, c.y);
path.lineTo(a.x, a.y);
path.close();
canvas.drawPath(path, paint);
/* paint.setTextSize(60);
canvas.drawText("h o m e",60,76,paint);*/
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec , resolveSize(itemHeight , heightMeasureSpec));
}
public String getCustomTag(){
return this.tag;
}
public String getColor(){
return bgColor +" ";
}
}
这是在RelativeLayout的在运行时添加自定义视图的方法:
private void drawViewsTest(int numItems,int screenWidth,int itemHeight,Context ctx)
{
Point firstPoint = new Point(0,0) ;
Point secondPoint = new Point (0,itemHeight);
Point thirdPoint = new Point (screenWidth,itemHeight/2);
view = new CustomView[numItems];
for(int i = 0; i < numItems; i++){
view[i] = new CustomView(ctx);
if(i%2 == 0){
view[i].setParameters(Color.BLACK, firstPoint, secondPoint, thirdPoint, secondPoint.y, "men" + " ");
view[i].startAnimation(an);
}else{
view[i].setParameters(Color.RED, firstPoint, secondPoint, thirdPoint, secondPoint.y, "women" + " ");
view[i].startAnimation(anTwo);
}
view[i].setId(i + 1);
view[i].setOnClickListener(this);
firstPoint = thirdPoint;
thirdPoint = secondPoint;
secondPoint = new Point(firstPoint.x , firstPoint.y+itemHeight);
rl.addView(view[i]);
}
setContentView(v);
}
我的问题是内部我为每个视图注册onClickListener,为每个视图注册setId。但在clicklistener里面,无论我点击哪个视图,都会返回最后添加视图的ID。 任何建议,将不胜感激。!
这是监听器代码
@Override
public void onClick(View view) {
Log.e("Tag is " , view.getId() +"");
}
显示你的听众代码 – 2015-02-10 09:22:22
发布监听功能! – 2015-02-10 10:23:20