package com.xxx.handlerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private ImageView imageView1;
private int marginLeft = 0;
private int marginBottom = 0;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
if (marginLeft == screenWidth) {
marginBottom = marginBottom > screenHeight ? 0
: (marginBottom + 30);
}
marginLeft = marginLeft == screenWidth ? 0 : (marginLeft + 1);
// marginLeft = 1;
// imageView1.offsetLeftAndRight(marginLeft);
imageView1.setX(marginLeft);
imageView1.setY(marginBottom);
textView1.setText("" + marginLeft + ":" + marginBottom);
break;
default:
break;
}
};
};
private int screenWidth;
private int screenHeight;
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;
imageView1 = (ImageView) findViewById(R.id.imageView1);
textView1 = (TextView) findViewById(R.id.textView1);
new Thread() {
public void run() {
while (true) {
SystemClock.sleep(1);
handler.sendEmptyMessage(0);
}
};
}.start();
}
}
<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"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/circle" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="158dp"
android:layout_toRightOf="@+id/imageView1"
android:text="TextView" />
</RelativeLayout>