我使用了四个按钮(上,下,左,右),我也有图像。我必须相应地移动图像时,我按向上按钮我应该向上移动图像,当我按左时同样保持两个方向它应该向左移动图像。我已经使用onclick监听器,然后我试图移动图像使用X,Y坐标。我不怎么把X,Y坐标。根据按钮点击移动图像
这是代码。
public class MainActivity extends Activity implements OnClickListener {
Button up,left,right,down;
ImageView i1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
up=(Button)findViewById(R.id.button1);
left=(Button)findViewById(R.id.button2);
right=(Button)findViewById(R.id.button3);
down=(Button)findViewById(R.id.button4);
i1=(ImageView)findViewById(R.id.imageView1);
up.setOnClickListener(this);
}
public void onClick(View arg0) {
Toast.makeText(getApplication(),"UP",5000).show();
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams)
i1.getLayoutParams();
int x = (int)getRawx();
int y = (int)getRawY();
mParams.leftMargin = x-50;
mParams.topMargin = y-50;
i1.setLayoutParams(mParams);
}
}
HI, 我已经更新代码下面请检查一下。
package com.example.motion;
public class MainActivity extends Activity implements OnClickListener {
Button up,left,right,down;
ImageView i1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
up=(Button)findViewById(R.id.button1);
left=(Button)findViewById(R.id.button2);
right=(Button)findViewById(R.id.button3);
down=(Button)findViewById(R.id.button4);
i1=(ImageView)findViewById(R.id.imageView1);
up.setOnClickListener(this);
down.setOnClickListener(this);
left.setOnClickListener(this);
right.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button1:
{
Toast.makeText(getApplication(),"UP",Toast.LENGTH_SHORT).show();
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams)
i1.getLayoutParams();
mParams.topMargin -= 20;
i1.setLayoutParams(mParams);
break;
}
case R.id.button4:
{
Toast.makeText(getApplication(),"DOWN",Toast.LENGTH_SHORT).show();
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams)
i1.getLayoutParams();
mParams.topMargin += 20;
i1.setLayoutParams(mParams);
break;
}
case R.id.button2:
{
Toast.makeText(getApplication(),"LEFT",Toast.LENGTH_SHORT).show();
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams)
i1.getLayoutParams();
mParams.leftMargin -= 20;
i1.setLayoutParams(mParams);
break;
}
case R.id.button3:
{
Toast.makeText(getApplication(),"RIGHT",Toast.LENGTH_SHORT).show();
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams)
i1.getLayoutParams();
mParams.leftMargin += 20;
i1.setLayoutParams(mParams);
break;
}
}
}
}
任何机构请回复 – 2013-04-06 09:24:13
告诉我要去的地方错了这是可能的原因是按当你改变x使用的onclick监听 – 2013-04-06 09:33:53
移动图像向上按钮?不应该只有y才能改变? – lelloman 2013-04-06 09:36:35