MBM*_*BMJ 3 android button touch
我想制作一个应用程序,每当我触摸屏幕时,屏幕一开始应该是空白的,就会创建一个按钮并弹出到屏幕上。所以我在这里尝试的是在 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;
}
};
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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>
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做?
如果您想在单击屏幕上的任何位置时添加按钮,我认为您可以使用相对布局并在该布局上添加触摸侦听器。在触摸该屏幕时,在该布局上添加按钮,以便在新触摸时弹出一个新按钮。谢谢
代码会像——
主要布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
Run Code Online (Sandbox Code Playgroud)
这堂课会像——
rl = (RelativeLayout) findViewById(R.id.rl);
rl.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
float x = event.getX()*event.getXPrecision();
float y = event.getY()*event.getYPrecision();
Button btn = new Button(getApplicationContext());
RelativeLayout.LayoutParams bp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
bp.leftMargin = (int) x;
bp.topMargin = (int) y;
btn.setLayoutParams(bp);
rl.addView(btn);
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2058 次 |
| 最近记录: |