Android - 如何点击自定义视图

时间:2016-06-24 14:07:35

标签: java android android-layout android-view

为了在所有设备上的确切位置定位按钮,我使用自定义视图创建了它。该按钮占据了屏幕的一小部分,但实际视图占据了大部分屏幕。按钮周围的所有区域都是透明的。如何让用户点击透明区域到下面的按钮,但仍然点击视图上的按钮区域?

以下是相关代码:

public class MainActivity extends AppCompatActivity {

final float dotScale = 0.3f;
Dot dot1, dot2;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.mainView);
MyView myView = new MyView(this);
myLayout.addView(myView);

// Two dots are created.

dot1 = new Dot(this);
dot1.xOffset = 2.9f;
dot1.yOffset = 3.3f;
myLayout.addView(dot1);
dot2 = new Dot(this);
dot2.xOffset = -2.4f;
dot2.yOffset = 1.1f;
myLayout.addView(dot2);

// Makes dots clickable

dot1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (!dot1.isClicked) {
            dot1.animate().setDuration(300).setInterpolator(new AnticipateInterpolator())
                    .scaleXBy(dotScale).scaleYBy(dotScale).alpha(1.0f);
            dot1.isClicked = true;
        }
    }
});

dot2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (!dot2.isClicked) {
            dot2.animate().setDuration(300).setInterpolator(new AnticipateInterpolator())
                    .scaleXBy(dotScale).scaleYBy(dotScale).alpha(1.0f);
            dot2.isClicked = true;
        }
    }
});

}

.......

//custom view for Dots

class Dot extends View {

int radius;
float xOffset;
float yOffset;
boolean isClicked = false;

public Dot(Context context) {
    super(context);
    setClickable(true);


}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int x = getWidth();
    int y = getHeight();
    double ratio = (547d / 828d);
    float circleX = (float)((x / 2) - (y * ratio) / xOffset);
    float circleY = (float)(y / yOffset);

    radius = (int)((float)y/13);
    setPivotX(circleX);
    setPivotY(circleY);

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawCircle(circleX, circleY, radius, paint);
}


}

1 个答案:

答案 0 :(得分:0)

您应该设置视图clickable并且不要覆盖onTouch或只是从中返回false。返回false表示您没有使用事件,它将被转发到视图层次结构中的下一个元素。