我想制作一个应用程序,每当我触摸屏幕时,它在开始时应该是空白的,一个按钮将被创建并弹出到屏幕上。所以我在这里尝试的是在 main.xml 中创建一个按钮并通过 id 调用它。然后我应用了这个方法。
public class TouchButtonActivity extends Activity {
Button b;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(Button) findViewById(R.id.b1);
b.setOnTouchListener(nextListener);
}
public OnTouchListener nextListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
float x = event.getX()*event.getXPrecision();
float y = event.getY()*event.getYPrecision();
FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
p.gravity = Gravity.TOP;
p.leftMargin = (int) x;
p.topMargin = (int) y;
b.setLayoutParams(p);
return true;
}
return false;
}
};
}
这是我的 xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="B" />
</FrameLayout>
我怎么能这样做?