我需要滾動自定義視圖。爲了達到這個目的,我在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