如何在android中获取主屏幕小部件列表项的点击事件[重复]

Posted

技术标签:

【中文标题】如何在android中获取主屏幕小部件列表项的点击事件[重复]【英文标题】:How to get Click event on List Item of Home Screen widget in android [duplicate] 【发布时间】:2018-07-23 11:29:15 【问题描述】:

问题

我现在在主屏幕上有一个带有 Listview 动态数据项的小部件 我可以在 listview 项目点击时获得点击事件吗? 因为我可以点击小部件上的另一个按钮,但点击列表项仍然没有成功。

SimpleWidgetProvider.Java

public class SimpleWidgetProvider extends AppWidgetProvider 
public static String UPDATE_ACTION = "ActionUpdateSinglenoteWidget";
public static final String TOAST_ACTION = "com.varshaaweblabs.estateblock.TOAST_ACTION";
public static final String EXTRA_ITEM = "com.varshaaweblabs.estateblock.EXTRA_ITEM";
private static final String MyButton1 = "mybutton1";
private static final String MyButton2 = "mybutton2";
static RemoteViews remoteViews;
public static SharedPreferences.Editor editor;
public static SharedPreferences pref;
public Call<Search_Response> registerResponseCall;
ArrayList<Listing> listItemList = new ArrayList<>();
Gson gson1 = new Gson();
public static GoogleMap mMap;
ArrayList<String> jarray = new ArrayList<>();
public Criteria criteria = new Criteria();

public void updateAppWidget(final Context context, final AppWidgetManager appWidgetManager,
                            final int appWidgetId) 
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

    pref = context.getSharedPreferences("estateblock", MODE_PRIVATE);
    editor = pref.edit();

    getData(context, MyButton1);
    remoteViews.setInt(R.id.btn_current, "setBackgroundColor", Color.MAGENTA);
    remoteViews.setInt(R.id.btn_home, "setBackgroundColor", Color.LTGRAY);
    remoteViews.setInt(R.id.btn_seeall, "setBackgroundColor", Color.MAGENTA);


    new Handler().postDelayed(new Runnable() 

        @Override
        public void run() 
            // Set up the collection
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) 
                setRemoteAdapter(context, remoteViews);
             else 
                setRemoteAdapterV11(context, remoteViews);
            
            // Instruct the widget manager to update the widget
            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
            remoteViews.setOnClickPendingIntent(R.id.btn_current, getPendingSelfIntent(context, MyButton1));
            remoteViews.setOnClickPendingIntent(R.id.btn_home, getPendingSelfIntent(context, MyButton2));
            remoteViews.setViewVisibility(R.id.progress, View.GONE);
            remoteViews.setViewVisibility(R.id.widget_list, View.VISIBLE);
            pushWidgetUpdate(context, remoteViews);
            notifyUpdate(context, remoteViews);

        
    , 5000);



@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) 
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) 

        updateAppWidget(context, appWidgetManager, appWidgetId);
    


    super.onUpdate(context, appWidgetManager, appWidgetIds);


@Override
public void onEnabled(Context context) 
    // Enter relevant functionality for when the first widget is created


@Override
public void onDisabled(Context context) 
    // Enter relevant functionality for when the last widget is disabled


/**
 * Sets the remote adapter used to fill in the list items
 *
 * @param views RemoteViews to set the RemoteAdapter
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private static void setRemoteAdapter(Context context, @NonNull final RemoteViews views) 
    views.setRemoteAdapter(R.id.widget_list,
            new Intent(context, WidgetService.class));




/**
 * Sets the remote adapter used to fill in the list items
 *
 * @param views RemoteViews to set the RemoteAdapter
 */
@SuppressWarnings("deprecation")
private static void setRemoteAdapterV11(Context context, @NonNull final RemoteViews views) 
    views.setRemoteAdapter(0, R.id.widget_list,
            new Intent(context, WidgetService.class));



protected PendingIntent getPendingSelfIntent(Context context, String action) 
    Intent intent = new Intent(context, getClass());
    intent.setAction(action);
    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) 


    ComponentName myWidget = new ComponentName(context, SimpleWidgetProvider.class);
    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    manager.updateAppWidget(myWidget, remoteViews);





public void notifyUpdate(Context context, RemoteViews remoteViews) 

    AppWidgetManager manager = AppWidgetManager.getInstance(context);
    int appWidgetIds[] = manager.getAppWidgetIds(
            new ComponentName(context, SimpleWidgetProvider.class));
    manager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list);


    hideProgress(remoteViews, context);



@Override
public void onReceive(Context context, Intent intent) 
    super.onReceive(context, intent);
    String action = intent.getAction();

    AppWidgetManager mgr = AppWidgetManager.getInstance(context);
    if (intent.getAction().equals(TOAST_ACTION)) 
        int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0);
        Toast.makeText(context, "Touched view " + viewIndex, Toast.LENGTH_SHORT).show();
    

    if (MyButton1.equals(intent.getAction())) 

        pref = context.getSharedPreferences("estateblock", MODE_PRIVATE);
        editor = pref.edit();
        listItemList.clear();
        updateData(context, MyButton1);


        Toast.makeText(context, "Current Criteria", Toast.LENGTH_SHORT).show();
    
    if (MyButton2.equals(intent.getAction())) 


        pref = context.getSharedPreferences("estateblock", MODE_PRIVATE);
        editor = pref.edit();
        listItemList.clear();
        updateData(context, MyButton2);

    




private void updateData(final Context context, String myButton) 

    if (myButton.equalsIgnoreCase("mybutton1")) 
        final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

        showProgress(remoteViews, context);
        remoteViews.setInt(R.id.btn_home, "setBackgroundColor", Color.LTGRAY);
        remoteViews.setInt(R.id.btn_current, "setBackgroundColor", Color.MAGENTA);

        Intent configIntent = new Intent(context, HomeActivity.class);

        configIntent.putExtra("widget", "Current");


        configIntent.setAction("current");

        PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        remoteViews.setOnClickPendingIntent(R.id.btn_seeall, configPendingIntent);

        Toast.makeText(context, "Current", Toast.LENGTH_SHORT).show();
        pushWidgetUpdate(context.getApplicationContext(), remoteViews);

        getData(context, MyButton1);


        new Handler().postDelayed(new Runnable() 

            @Override
            public void run() 


                notifyUpdate(context.getApplicationContext(), remoteViews);

            
        , 3500);

    

    if (myButton.equalsIgnoreCase("mybutton2")) 
        final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

        showProgress(remoteViews, context);
        remoteViews.setInt(R.id.btn_home, "setBackgroundColor", Color.MAGENTA);
        remoteViews.setInt(R.id.btn_current, "setBackgroundColor", Color.LTGRAY);

        Intent configIntent1 = new Intent(context, HomeActivity.class);

        configIntent1.putExtra("widget", "Home");

        configIntent1.setAction("Home");


        PendingIntent configPendingIntent1 = PendingIntent.getActivity(context, 1, configIntent1, PendingIntent.FLAG_UPDATE_CURRENT);


        remoteViews.setOnClickPendingIntent(R.id.btn_seeall, configPendingIntent1);


        Toast.makeText(context, "All Homes", Toast.LENGTH_SHORT).show();

        pushWidgetUpdate(context.getApplicationContext(), remoteViews);
        getData(context, MyButton2);


        new Handler().postDelayed(new Runnable() 

            @Override
            public void run() 

                notifyUpdate(context.getApplicationContext(), remoteViews);
            
        , 3500);

    

ListProvider.java

public class ListProvider implements RemoteViewsService.RemoteViewsFactory 

private Context context = null;
private int appWidgetId;
List<Listing> list = new ArrayList<>();
List<String> mCollection = new ArrayList<>();
public static List<Listing> listItemList = new ArrayList<>();
SharedPreferences.Editor editor;
SharedPreferences pref;
Gson gson = new Gson();


public ListProvider(Context context, Intent intent) 

    this.context = context;


    pref = context.getSharedPreferences(Utility.APP_NAME, MODE_PRIVATE);
    editor = pref.edit();
    Log.e("Constructor", "Called");
    populateListItem();




public void populateListItem() 

    listItemList.clear();

    String arrayListString = pref.getString("widget", "");
    Type type = new TypeToken<ArrayList<Listing>>() 
    .getType();

    listItemList = gson.fromJson(arrayListString, type);




@Override
public int getCount() 
    return listItemList.size();


@Override
public long getItemId(int position) 
    return position;


@Override
public RemoteViews getViewAt(final int position) 
    final RemoteViews remoteView = new RemoteViews(
            context.getPackageName(), R.layout.grid_view);

    Bitmap image = null;
    try 
        URL url = new URL(listItemList.get(position).getPrimaryPhoto().getUrl().getThumb());
        image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
     catch (IOException e) 
        Log.e("Image_load", e.getMessage());
    
    remoteView.setImageViewBitmap(R.id.widget_item_app_icon, image);
    remoteView.setTextViewText(R.id.heading, listItemList.get(position).getPriceForMap());
    remoteView.setTextViewText(R.id.address, listItemList.get(position).getArea());


    Intent intent = new Intent(context, Propertyfulldetailactivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    intent.putExtra(Utility.LISTING_KEY, listItemList.get(position).getListingKey());
    Bundle args = new Bundle();
    args.putSerializable("ARRAYLIST", (Serializable) listItemList.get(position));
    intent.putExtra("BUNDLE", args);
    remoteView.setOnClickPendingIntent(R.id.widget_item_app_icon, pendingIntent);


    return remoteView;



@Override
public RemoteViews getLoadingView() 
    return null;


@Override
public int getViewTypeCount() 
    return 1;


@Override
public boolean hasStableIds() 
    return true;


@Override
public void onCreate() 


    Log.e("onCreate", "Called");
    populateListItem();



@Override
public void onDataSetChanged() 

    populateListItem();


@Override
public void onDestroy() 

所以请参考我的代码并尝试帮助我解决这个问题。

【问题讨论】:

您要关闭您的应用并显示手机的主屏幕吗? 如果我点击 listView 项目然后打开其他活动?? 是的,当应用程序被杀死时,我想从小部件上下文中打开其他活动。 accepted answer on the first linked duplicate 清楚地说明了您需要做什么。下次,从一开始就将您的代码包含在问题中。 在您的问题中,为什么其他用户提供了代码,因此提供了 >90% 的内容? 【参考方案1】:

在列表视图中添加项目点击侦听器非常简单。您只需查看android List-view 链接即可。

【讨论】:

他不是要求活动。在小部件中为 listeview 设置监听器是不同的...

以上是关于如何在android中获取主屏幕小部件列表项的点击事件[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Android 无法使用列表视图加载主屏幕小部件

如何将值从主屏幕小部件传递给应用程序?

如何从 android 主屏幕小部件启动活动

Android主屏幕小部件中的RecyclerView [重复]

从原生 Android 主屏幕小部件调用 Flutter (Dart) 代码

如何从我的应用程序将小部件添加到 Android 主屏幕?