按下小部件ListView项时Android启动活动 [英] Android start activity when pressing widget ListView item

查看:59
本文介绍了按下小部件ListView项时Android启动活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ListView小部件,我希望用户在单击ListView时能够启动活动.我还没有找到任何关于此的教程,所以我想知道是否有人可以指出正确的方向或共享一些代码.无论单击哪个ListItem,我都想启动相同的活动,所以这不是问题.

I'm working on a ListView widget where I want the user to be able to launch a activity when the ListView is clicked. I haven't been able to find any sort of tutorial on this so I'm wondering if anyone could point me in the right direction or perhaps share some code. I want to launch the same activity regardless of which ListItem is clicked so that's not a problem.

感谢所有帮助!

推荐答案

看看

Have a look here and scroll to the subheading Adding behavior to individual items.

您需要确保同时从AppWidgetProvider setOnClickFillInIntent()实现中调用setPendingIntentTemplate().

You need to make sure you call both setPendingIntentTemplate() from your AppWidgetProvider and setOnClickFillInIntent() from your RemoteViewsService.RemoteViewsFactory implementation.

例如:

public class Widget extends AppWidgetProvider {

    // ...

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        for(int i = 0; i < appWidgetIds.length; i++){

            RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.widget);

            Intent startActivityIntent = new Intent(context, myActivity.class);
            PendingIntent startActivityPendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            widget.setPendingIntentTemplate(R.id.list_view, startActivityPendingIntent);

            appWidgetManager.updateAppWidget(appWidgetIds[i], widget);

            // ...
    }
}

public class WidgetAdapter implements RemoteViewsService.RemoteViewsFactory {

    // ...

    @Override
    public RemoteViews getViewAt(int position) {

    RemoteViews widgetRow = new RemoteViews(context.getPackageName(), R.layout.widget_row);

        Intent fillInIntent = new Intent();
        fillInIntent.putExtra(Widget.EXTRA_LIST_VIEW_ROW_NUMBER, position);
        widgetRow.setOnClickFillInIntent(R.id.list_view_row, fillInIntent);

        // ...

        return widgetRow;
    }
}

StackWidget示例中还有一个更确定的示例,该示例位于 SDK示例中,尽管我发现查找起来有些困难(有关说明,请参见此处) .它创建一个意图来显示Toast消息,但是使用相同的代码.

There is a more conclusive example in the StackWidget sample which is in the SDK samples, although I found it somewhat difficult to find (see here for directions). It creates an intent to show a Toast message, but it uses the same code.

这篇关于按下小部件ListView项时Android启动活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆