我有一个占据屏幕一部分的SurfaceView,以及底部的一些按钮。当按下按钮并且用户拖动时,我希望能够将图片(基于按钮)拖动到SurfaceView上并将其绘制到那里。
我希望能够使用clickListeners等,而不仅仅是有一个巨大的SurfaceView,我可以编写代码来检测用户按下的位置以及是否是按钮等。
我有一些解决方案,但对我来说似乎有点黑客攻击。智能地使用框架实现这一目标的最佳方法是什么?
我的部分XML:
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
<!-- Place buttons along the bottom -->
<RelativeLayout android:id="@+id/bottom_bar"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:layout_alignParentBottom="true"
android:background="@null">
<ImageButton android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="@null"
android:src="@drawable/btn_1">
</ImageButton>
<!-- More buttons here... -->
</RelativeLayout>
<!-- Place the SurfaceView in a frame so we can stack on top of it -->
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:layout_above="@id/bottom_bar">
<com.project.question.MySurfaceView
android:id="@+id/my_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</FrameLayout>
MySurfaceView中的相关Java代码,它扩展了SurfaceView。 mTouchX和Y在onDraw方法中用于绘制图像:
@Override
public boolean onTouchEvent(MotionEvent event){
mTouchX = (int) event.getX();
mTouchY = (int) event.getY();
return true;
}
public void onButtonTouchEvent(MotionEvent event){
event.setLocation(event.getX(), event.getY() + mScreenHeight);
onTouchEvent(event);
}
最后,活动:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.my_surface);
mView = (MySurfaceView) findViewById(R.id.my_view);
mSurfaceHeight = mView.getHeight();
mBtn = (ImageButton) findViewById(R.id.btn_1);
mBtn.setOnTouchListener(mTouchListener);
}
OnTouchListener mTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int [] location = new int[2];
v.getLocationOnScreen(location);
event.setLocation(event.getX() + location[0], event.getY());
mView.onButtonTouchEvent(event);
return true;
}
};
奇怪的是,必须在活动中添加x坐标,然后添加到View中的y坐标。否则,它不会显示在正确的位置。如果您不添加任何内容,使用mTouchX和mTouchY绘制的内容将显示在SurfaceView的左上角。
任何方向都将不胜感激。如果我以完全错误的方式解决这个问题,那也是很好的信息。
答案 0 :(得分:0)
我不确定我是否完全理解你要做的事情,但无论如何我都会试着给你一些有用的信息:
你的主要问题是坐标吗?
你可以在一切之上有一个看不见的视图(这是一个丑陋的解决方案),或者你可以使用一些数学。您可以获得视图的坐标,以及有关显示大小和总视图大小的信息,可以为您提供所需的所有信息
如前所述,我不完全确定您遇到问题的地方,但在我看来,您的方法似乎很好。
哦,还有一件事:
您应该尝试使用名为ACTION_MOVE的MotionEvent
float x = event.getX();
float y = event.getY();
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
//DO SOMETHING
case MotionEvent.ACTION_MOVE:
//DO SOMETHING using x and y.
}