【发布时间】:2017-09-11 20:28:53
【问题描述】:
我写在这里是因为我在 Android Studio 中有一个非常烦人的问题。 我的“应用程序”非常简单,一页有 13 个按钮;我想要的很简单:当我单击第 13 个按钮时,一个一个地更新前十二个按钮。 我希望看到按钮在每个按钮之间有一点间隔更新,但我不明白该怎么做。 我在“onClick”方法中尝试了很多技巧,但我不知道如何解决它;我得到的是,经过一段时间(获得的时间将我放入函数中的各种“睡眠”加起来)所有按钮同时变为彩色。 我进行了最后一次尝试,但如果您有任何其他方式可以做到这一点,我愿意改变方式继续进行。
int[] buttonIDs = new int[] {R.id.button1, R.id.button2, R.id.button3, R.id.button4, R.id.button5, R.id.button6, R.id.button7,
R.id.button8, R.id.button9, R.id.button10, R.id.button11, R.id.button12 };
int currentI = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button goButton = (Button) findViewById(R.id.button13);
goButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentI < buttonIDs.length) {
Button b = (Button) findViewById(buttonIDs[currentI]);
b.setBackgroundColor(Color.parseColor("#FF22FF"));
currentI++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t = new Thread() {
public void run() {
goButton.performClick();
}
};
t.start();
}
}
});
}
此尝试的结果是第一个按钮变为彩色,然后我在 Android 模拟器上收到“应用程序已停止”错误。
提前致谢
【问题讨论】:
-
你不应该睡在 UI 线程上。这只会阻止 UI 响应。
-
即使我删除它,应用程序也会崩溃。此外,我需要一种方法来逐个着色按钮,因此我设置了睡眠(我什至尝试将“睡眠”放在线程 t 的“运行”方法中,但它不会改变任何东西。
-
UI 线程负责对按钮进行树形更改。通过休眠 UI 线程,您将阻止这些更改生效。所以这绝对不是正确的解决方案。有关一些建议,请参阅下面的两个答案。两者都不完整,但希望它们能帮助您朝着正确的方向前进。
标签: android multithreading android-activity onclicklistener background-color