我想知道如何每秒更改一次ImageButton的位置。我希望这个职位每次都是随机的。我不知道从哪里开始实现这一目标。有什么建议吗?
答案 0 :(得分:0)
也许这会给你一些想法
activity_main.xml中
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/button"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="I am button"/>
</RelativeLayout>
MainActivity.java
package com.com.randombutton;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton button = (ImageButton) findViewById(R.id.button);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Random rand = new Random();
while (true) {
Log.e("TAG", "thread");
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) button.getLayoutParams();
params.setMargins(rand.nextInt(500), rand.nextInt(500), 0, 0);
try {
Thread.sleep(1000);
} catch (Exception e) {
}
button.post(new Runnable() {
@Override
public void run() {
button.requestLayout(); //has to be called in UI thread
}
});
}
}
});
thread.start();
}
}
这个想法非常简单。制作一个线程,移动视图并使其进入休眠状态1秒钟。可能有更好的方法来移动视图本身。