我在我的应用程序中使用与本文相同的菜单...我使用图库 View 来显示我的菜单项。
问题是,我为画廊实现了 onItemSelected
监听器,以便在选择新项目时加载与该主题相关的数据。 但我也想允许用户完全滚动图库。但是每次当用户移动到下一个项目时,就会调用 onItemSelected()
函数并开始加载数据。
我想做的就是在 onItemSelected()
函数中添加一些延迟,这样,如果在该延迟之间用户滚动下一个项目,则不需要加载前一个项目的数据,但对于当前的。时间可以是1秒。如果用户在 1 秒内没有转到下一个项目,则必须加载该项目的数据。
有人可以帮忙吗?我想启动一个线程,但是每次 onItemSelected()
都会有新的线程...
我也尝试过
public class TimerThreadForCategoriesMenu extends Thread{
int old = -1;
int cur = -1;
CategoriesActivity catAct = null;
public TimerThreadForCategoriesMenu(CategoriesActivity act , int cu) {
this.cur = cu;
old = cu;
this.catAct = act;
}
@Override
public void run() {
Looper.prepare();
do{
old = this.cur;
for(int i = 0; i<15; i++){
try{
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
}
}while(cur != old);
catAct.performTask();
Looper.loop();
}
public void setCur (int curr){
this.cur = curr;
}
}
并在OnItemSelected()
if(timer == null){
timer = new TimerThreadForCategoriesMenu(this, arg2);
timer.start();
}
timer.setCur(curInd);
发现异常:
11-24 16:48:50.046: ERROR/AndroidRuntime(8049): Uncaught handler: thread Thread-8 exiting due to uncaught exception
11-24 16:48:50.126: ERROR/AndroidRuntime(8049): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-24 16:48:50.126: ERROR/AndroidRuntime(8049): at android.view.ViewRoot.checkThread(ViewRoot.java:2683)
11-24 16:48:50.126: ERROR/AndroidRuntime(8049): at android.view.ViewRoot.invalidateChild(ViewRoot.java:570)
11-24 16:48:50.126: ERROR/AndroidRuntime(8049): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:596)
11-24 16:48:50.126: ERROR/AndroidRuntime(8049): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2396)
11-24 16:48:50.126: ERROR/AndroidRuntime(8049): at android.view.View.invalidate(View.java:4945)
11-24 16:48:50.126: ERROR/AndroidRuntime(8049): at
最佳答案
使用Handler
和postDelayed()
一个Runnable
编辑:
这取决于您想要进行什么处理。
查看引用文献中的Looper
。 UI 有自己的 Looper
,因此您无需创建一个。只需创建一个 Handler
,但是发布到 UI 线程处理程序的任何 Runnable
都将在 UI 线程上运行。如果您正在做的事情需要一段时间才能完成,请使用 Handler
创建您自己的 Thread
并将 Runnables
发布到该线程。
http://developer.android.com/reference/android/os/Looper.html
编辑:
因此,请在您的 Activity 中创建成员。
Handler handler;
MyLooper mylooper;
你的线程循环器。
class MyLooper extends Thread {
public Handler handler;
public void run() {
Looper.prepare();
handler = new Handler() {
public void handleMessage(Message msg) {}
};
Looper.loop();
}
}
在您的Activity.onCreate
中。
handler = new Handler();
mylooper = new MyLooper();
现在创建Runnable
。
Runnable processinfo = new Runnable() {
public void run() {
// your processing here
}
}
Runnable updateui = new Runnable() {
public void run() {
// update ui component here
}
}
现在让这些Runnables
执行。
mylooper.handler.postDelayed(processinfo, 1000);
handler.post(updateui);
您将需要一些逻辑来根据延迟的需要来处理取消Runnable
。
关于java - 如何在android中设置 "onItemSelected()"函数的延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4263830/