我正试图在点击时移动图像按钮的位置。我尝试了以下但它在“rlOut.addView(imgP,p);”崩溃了。在onCreate()中运行它们没有问题。
公共类Delet3Activity扩展了Activity {
RelativeLayout rlOut;
ImageButton imbBtn;
EditText et1, et2;
ImageView ivB;
ImageButton imgP;
RelativeLayout.LayoutParams p;
RelativeLayout.LayoutParams params;
int mX, mY;
@覆盖
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
imbBtn = (ImageButton)findViewById(R.id.imgBtn);
rlOut = (RelativeLayout)findViewById(R.id.rlOut);
imgP = (ImageButton)findViewById(R.id.imgP);
ivB = new ImageView(this);
ivB.setBackgroundColor(Color.RED);
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
width = width/2-62;
height = height/2-62;
p = new RelativeLayout.LayoutParams(62, 62);
imbBtn.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
LayoutParams par = (LayoutParams)imbBtn.getLayoutParams();
if(event.getAction()==MotionEvent.ACTION_DOWN)
{
Log.d("ok","down");
mX = (int) event.getX() - imbBtn.getWidth() / 2;
mY = (int) event.getY() - imbBtn.getHeight() / 2;
et1.setText("mX down: "+String.valueOf(mX));
et2.setText("mY down: "+String.valueOf(mY));
}
else if (event.getAction()==MotionEvent.ACTION_UP)
{
Log.d("ok","up");
rlOut.addView(ivB, params);
p.leftMargin=4;
params.leftMargin = 60;
params.topMargin = 20;
rlOut.addView(imgP, p);
Log.d("ok","p");
}
else if (event.getAction()==MotionEvent.ACTION_MOVE)
{
Log.d("ok","move");
mX = (int) event.getX() - imbBtn.getWidth() / 2;
mY = (int) event.getY() - imbBtn.getHeight() / 2;
et1.setText("mX move: "+String.valueOf(mX));
et2.setText("mY move: "+String.valueOf(mY));
}
return false;
}
});
} }
答案 0 :(得分:0)
OnCreate
方法是您设置setContentView(R.layout.main)
的地方。我认为变量rlOut
代表RelativeLayout
,它可能位于您的主要布局中。在设置contentView并使用rlOut
初始化变量findViewById
后,在OnCreate方法中调用上述函数。或者,如果变量rlOut
位于其他布局文件中,则您必须首先使用布局过热器对该布局进行充气,然后使用findViewById
方法查找该视图。
希望这有帮助。
修改强>
以下代码应该是您正在寻找的解决方案:
imbBtn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams par = (LayoutParams)imbBtn.getLayoutParams();
if (event.getAction()==MotionEvent.ACTION_MOVE)
{
Log.d("ok","move");
mX = (int) event.getX() - imbBtn.getWidth() / 2;
mY = (int) event.getY() - imbBtn.getHeight() / 2;
par.leftMargin = imbBtn.getLeft() + mX;
par.topMargin = imbBtn.getTop() + mY;
imbBtn.setLayoutParams(par);
et1.setText("mX move: "+String.valueOf(mX));
et2.setText("mY move: "+String.valueOf(mY));
}
return false;
}
});
MotionEvent.ACTION_MOVE
是您需要捕获的唯一事件。希望这个解决方案对您有所帮助。