我怎么能这样做setOnTouchListener()方法仅适用于自定义视图

时间:2015-09-02 09:13:40

标签: android

我有RectangleLarger_Rectangle个类。现在,当我只触摸rectangle类中的矩形对象时,我希望这样做,因为我看到Larger_Rectangle类中的其他矩形对象。

Rectangle.class

public class Rectangle extends View {
Paint paint;
Rectangle(Context context) {
super(context);
paint = new Paint();
}
@Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.RED);
canvas.drawRect(10,30,50,70,paint);
}
}

Larger_Rectangle类

public class Larger_Rectangle extends View {
Paint paint;
Larger_Rectangle(Context context) {
super(context);
paint = new Paint();
}
@Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.BLUE);
canvas.drawRect(60,100,120,150,paint);
}
}

MainActivity类

public class MainActivity extends Activity {
Rectangle rectangle;
Larger_Rectangle larger_rectangle;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
rectangle = new Rectangle(this);
setContentView(rectangle);
rectangle.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        larger_rectangle = new Larger_Rectangle(getApplicationContext());
        setContentView(larger_rectangle);

        return true;
    }
});
}
}

我想当我只触摸矩形对象时,我可以看到greater_rectangle对象,但是当我触摸触摸屏中的任何地方时,我会看到greater_rectangle对象。

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,您的视图应该是一个类......

MainActivity.java

public class MainActivity extends Activity {
Rectangle rectangle;
Larger_Rectangle larger_rectangle;
@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    rectangle = new Rectangle(this);
    setContentView(rectangle);
    rectangle.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            larger_rectangle = new Larger_Rectangle(getApplicationContext());
            setContentView(larger_rectangle);

            return true;
        }
    });
}

}

Rectangle.java

public class Rectangle extends View {
Paint paint;

Rectangle(Context context) {
    super(context);
    paint = new Paint();
}

@Override
public void onDraw(Canvas canvas) {
    paint.setColor(Color.RED);
    canvas.drawRect(10,30,50,70,paint);
}

}

最后是Large_Rectangle.java ......

public class Larger_Rectangle extends View {
Paint paint;

Larger_Rectangle(Context context) {
    super(context);
    paint = new Paint();
}

@Override
public void onDraw(Canvas canvas) {
    paint.setColor(Color.BLUE);
    canvas.drawRect(60,100,120,150,paint);
}

}