简单实现一个背景移动,直接贴代码
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
>
<ImageView
android:id="@+id/img3"
android:layout_below="@+id/img_show2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
private ImageView imgshow2;
private Bitmap bitmap;
private int with=500;
private int start=0;
private Handler handler = new Handler() {
@SuppressLint("NewApi") public void handleMessage(android.os.Message msg) {
if (msg.arg1 == 1) {
imgshow2.setBackground(null);
imgshow2.setBackground(new BitmapDrawable((Bitmap) msg.obj));
}
};
};
@SuppressLint("NewApi") @SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WindowManager dpManager=(WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
Log.d("scremwith", dpManager.getDefaultDisplay().getWidth()+"");
Log.d("scremheight", dpManager.getDefaultDisplay().getHeight()+"");
imgshow2=(ImageView) findViewById(R.id.img3);
final Timer time2 = new Timer();
time2.schedule(new TimerTask() {
@SuppressWarnings("static-access")
@Override
public void run() {
// TODO Auto-generated method stub
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.clicptest);
Log.d("with", with+"");
//Log.d("bitmap.getWidth()/2", bitmap.getWidth()/2+"");
if (with>=bitmap.getWidth()/2 || start>=bitmap.getWidth()/2 ) {
with=500;
start=0;
//time2.cancel();
}
if (with<bitmap.getWidth()/2 || start<bitmap.getWidth()/2 ) {
Message message=new Message();
message.arg1=1;
message.obj=bitmap.createBitmap(bitmap, start, 0, with, bitmap.getHeight());
handler.sendMessage(message);
with+=1;
start+=1;
}
}
}, 0, 100);
}
}
这段代码相当基础,相信大家都看得懂,就是一个定时器timer和一个createBitmap()方法,具体用法可以参考api。