Android RemoteViews ListView Scroll

前端 未结 4 1939
花落未央
花落未央 2021-01-01 06:01

Im trying to scroll a ListView to a particular position in an AppWidget.

However it does not do anything, i also tried the setPosit

4条回答
  •  长情又很酷
    2021-01-01 06:57

    Issue: ListView does not have any children until it is displayed. Hence calling setScrollPosition right after setting adpater has no effect. Following is the code in AbsListView which does this check:

    final int childCount = getChildCount();
    if (childCount == 0) {
        // Can't scroll without children.
        return;
    }
    

    Solution: Ideally I would have used ViewTreeObserver.OnGlobalLayoutListener for setting the ListView scroll position, but it is not possible in case of remote views. Set the scroll position and invoke partiallyUpdateAppWidget in a runnable with some delay. I've modified the Android weather widget code and shared in git hub.

    public class MyWidgetProvider extends AppWidgetProvider {
    
        private static HandlerThread sWorkerThread;
        private static Handler sWorkerQueue;
    
        public MyWidgetProvider() {
            // Start the worker thread
            sWorkerThread = new HandlerThread("MyWidgetProvider-worker");
            sWorkerThread.start();
            sWorkerQueue = new Handler(sWorkerThread.getLooper());
        }
    
        public void onUpdate(Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {
            for (int i = 0; i < appWidgetIds.length; ++i) {
                ...
                final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
                views.setRemoteAdapter(R.id.lvWidget, svcIntent);
    
                sWorkerQueue.postDelayed(new Runnable() {
    
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        views.setScrollPosition(R.id.list, 3);
                        appWidgetManager.partiallyUpdateAppWidget(appWidgetIds[i], views);
                    }
    
                }, 1000);
    
                appWidgetManager.updateAppWidget(appWidgetIds[i], views);
                ...
            }
        }
    }
    

    Here is the screen record. It scrolls to 5th position.

    Auto scrolling of ListView in app widget

提交回复
热议问题