我使用了四个按钮(上、下、左、右),我也有图像。当我按下 UP 按钮时,我必须相应地移动图像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);
}
}
嗨,我已经更新了下面的代码,请检查它。
包 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;
}
}
}
}