【发布时间】:2015-03-08 23:23:54
【问题描述】:
我正在努力学习 Android 编程,到目前为止一切都很好。现在我正在尝试学习有关线程的知识,但我的代码无法正常工作。
我已经读过了
http://developer.android.com/guide/faq/commontasks.html#threading http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html#concurrency_handler
我尝试同时使用这两种方法来使我的代码正常工作,但我不知道该怎么做,因为它们都不符合我的需求,并且都使用相同的进度条示例。
我的布局中有 3 个按钮,我想(慢慢地)向上或向下移动。我想用一个线程来做这件事,因为 mainUI 活动在这样做时不应该停止工作。 所以我的想法是启动一个新线程,在其中等待一段时间,然后设置参数,然后我一次又一次地这样做。
我可能可以用全局变量来解决它,但我不想用这种“便宜”的技巧来解决这样的问题。
我的代码看起来像这样(大部分是从两侧复制的,因为我找不到为方法提供参数的线程的工作示例)
public class MainActivity extends Activity {
// Need handler for callbacks to the UI thread
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateResultsInUi();
}
};
protected void moveMenu(int direction, final int time) {
// Fire off a thread to do some work that we shouldn't do directly in the UI thread
Thread t = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
doSomethingExpensive(time);
mHandler.post(mUpdateResults); // <--- Here im looking for a way to give i to the updateResultsInUi() Method
}
}
};
t.start();
}
private void updateResultsInUi(int i) {
// Back in the UI thread -- update our UI elements based on the data in mResults
ScrollView topScrollView = (ScrollView) findViewById(R.id.scrollView1);
LinearLayout botLinearLayout = (LinearLayout) findViewById(R.id.LinearLayoutButton);
LinearLayout.LayoutParams paramsScrollView = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,0,90+i);
LinearLayout.LayoutParams paramsLinearLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,0,10-i);
topScrollView.setLayoutParams(paramsScrollView);
botLinearLayout.setLayoutParams(paramsLinearLayout);
}
// Simulating something timeconsuming
private void doSomethingExpensive(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void button_click_del(View v)
{
[...]
moveMenu(direction, time);
}
[...]
}
【问题讨论】:
标签: java android multithreading methods parameters