我说的意思是 创建一个 透明View 设置View窗口大小 且可以触摸 且监听触摸
事件,可以在这个View上添加其他控件或者绘制自定义图形。
具体实现步骤如下:
-
创建一个自定义View,继承自View或者其子类,比如RelativeLayout、FrameLayout等。
-
在构造方法中设置View的背景为透明,可以使用setBackgroundColor(Color.TRANSPARENT)方法实现。
-
重写onMeasure方法,设置View的宽高,可以使用MeasureSpec.EXACTLY或者MeasureSpec.AT_MOST等模式。
-
重写onTouchEvent方法,监听触摸事件,可以使用MotionEvent.ACTION_DOWN、MotionEvent.ACTION_MOVE和MotionEvent.ACTION_UP等事件。
-
在View中添加其他控件或者绘制自定义图形,可以在onDraw方法中实现。
-
将自定义View添加到Activity中,可以使用addView方法或者在xml布局文件中引入。
示例代码如下:
public class TransparentView extends View {
public TransparentView(Context context) {
super(context);
init();
}
public TransparentView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TransparentView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setBackgroundColor(Color.TRANSPARENT);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width = 0;
int height = 0;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(width, widthSize);
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, heightSize);
}
setMeasuredDimension(width, height);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// 处理按下事件
break;
case MotionEvent.ACTION_MOVE:
// 处理移动事件
break;
case MotionEvent.ACTION_UP:
// 处理抬起事件
break;
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制自定义图形或者添加其他控件
}
}
将自定义View添加到Activity中的示例代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TransparentView transparentView = new TransparentView(this);
transparentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
((FrameLayout) findViewById(R.id.container)).addView(transparentView);
}
}
在xml布局文件中引入自定义View的示例代码如下:
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.TransparentView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
``
原文地址: http://www.cveoy.top/t/topic/ckFO 著作权归作者所有。请勿转载和采集!