android button 坐标,android – 根据Button单击移动图像

我使用了四个按钮(向上,向下,向左,向右),我也有图像.我必须相应地移动图像,当我按下向上按钮我应该向上移动图像,当我按左侧同样保持两个方向它应该向左移动图像.我使用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;

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值