Example usage for android.widget RemoteViews addView

List of usage examples for android.widget RemoteViews addView

Introduction

In this page you can find the example usage for android.widget RemoteViews addView.

Prototype

public void addView(int viewId, RemoteViews nestedView) 

Source Link

Document

Equivalent to calling ViewGroup#addView(View) after inflating the given RemoteViews .

Usage

From source file:android.support.v7.app.NotificationCompatImplBase.java

private static <T extends NotificationCompatBase.Action> RemoteViews generateBigContentView(Context context,
        CharSequence contentTitle, CharSequence contentText, CharSequence contentInfo, int number,
        Bitmap largeIcon, CharSequence subText, boolean useChronometer, long when, List<T> actions,
        boolean showCancelButton, PendingIntent cancelButtonIntent) {
    final int actionCount = Math.min(actions.size(), MAX_MEDIA_BUTTONS);
    RemoteViews big = applyStandardTemplate(context, contentTitle, contentText, contentInfo, number, largeIcon,
            subText, useChronometer, when, getBigLayoutResource(actionCount), false /* fitIn1U */);

    big.removeAllViews(R.id.media_actions);
    if (actionCount > 0) {
        for (int i = 0; i < actionCount; i++) {
            final RemoteViews button = generateMediaActionButton(context, actions.get(i));
            big.addView(R.id.media_actions, button);
        }/*  w  ww . j  av a2s . com*/
    }
    if (showCancelButton) {
        big.setViewVisibility(R.id.cancel_action, View.VISIBLE);
        big.setInt(R.id.cancel_action, "setAlpha",
                context.getResources().getInteger(R.integer.cancel_button_image_alpha));
        big.setOnClickPendingIntent(R.id.cancel_action, cancelButtonIntent);
    } else {
        big.setViewVisibility(R.id.cancel_action, View.GONE);
    }
    return big;
}

From source file:cat.mvmike.minimalcalendarwidget.service.DayService.java

public static void setDays(final Context context, final Calendar cal, final SpannableString ss,
        final RemoteViews remoteViews) {

    int firstDayOfWeek = ConfigurationService.getStartWeekDay(context);
    Theme theme = ConfigurationService.getTheme(context);
    CalendarStatus cs = new CalendarStatus(context, cal, firstDayOfWeek);

    Set<InstanceDto> instanceSet = PermissionsActivity.isPermitted(context)
            ? CalendarResolver.readAllInstances(context.getContentResolver(), cal)
            : new HashSet<>();

    RemoteViews rowRv;
    for (int week = 0; week < NUM_WEEKS; week++) {

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

        DayStatus ds;//from   w  w w.  j a v  a 2 s  .  co  m
        for (int day = 0; day < Calendar.DAY_OF_WEEK; day++) {

            ds = new DayStatus(cal, cs.getTodayYear(), cs.getThisMonth(), cs.getToday());
            RemoteViews cellRv = new RemoteViews(context.getPackageName(), getDayLayout(theme, ds));

            int numberOfInstances = getNumberOfInstances(instanceSet, ds);
            setInstanceNumber(context, cellRv, Integer.toString(ds.getDayOfMonth()), ds.isToday(),
                    numberOfInstances);
            checkMonthBeginningStyleChange(cs.getCalendar(), cellRv, ss);

            cs.getCalendar().add(Calendar.DAY_OF_MONTH, 1);

            rowRv.addView(R.id.row_container, cellRv);
        }

        remoteViews.addView(R.id.calendar_widget, rowRv);
    }
}

From source file:android.support.v7.app.NotificationCompatImplBase.java

private static <T extends NotificationCompatBase.Action> RemoteViews generateContentView(Context context,
        CharSequence contentTitle, CharSequence contentText, CharSequence contentInfo, int number,
        Bitmap largeIcon, CharSequence subText, boolean useChronometer, long when, List<T> actions,
        int[] actionsToShowInCompact, boolean showCancelButton, PendingIntent cancelButtonIntent) {
    RemoteViews view = applyStandardTemplate(context, contentTitle, contentText, contentInfo, number, largeIcon,
            subText, useChronometer, when, R.layout.notification_template_media, true /* fitIn1U */);

    final int numActions = actions.size();
    final int N = actionsToShowInCompact == null ? 0
            : Math.min(actionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
    view.removeAllViews(R.id.media_actions);
    if (N > 0) {
        for (int i = 0; i < N; i++) {
            if (i >= numActions) {
                throw new IllegalArgumentException(String.format(
                        "setShowActionsInCompactView: action %d out of bounds (max %d)", i, numActions - 1));
            }/*  w  w w.j  av  a2s . c  o m*/

            final NotificationCompatBase.Action action = actions.get(actionsToShowInCompact[i]);
            final RemoteViews button = generateMediaActionButton(context, action);
            view.addView(R.id.media_actions, button);
        }
    }
    if (showCancelButton) {
        view.setViewVisibility(R.id.end_padder, View.GONE);
        view.setViewVisibility(R.id.cancel_action, View.VISIBLE);
        view.setOnClickPendingIntent(R.id.cancel_action, cancelButtonIntent);
        view.setInt(R.id.cancel_action, "setAlpha",
                context.getResources().getInteger(R.integer.cancel_button_image_alpha));
    } else {
        view.setViewVisibility(R.id.end_padder, View.VISIBLE);
        view.setViewVisibility(R.id.cancel_action, View.GONE);
    }
    return view;
}

From source file:com.oasisfeng.nevo.decorators.bundle.BundleDecorator.java

/** Preview the last a few notifications vertically as expanded view of bundle notification. */
private RemoteViews buildExpandedView(final List<StatusBarNotificationEvo> sbns) {
    if (sbns.isEmpty())
        return null;
    final RemoteViews expanded = new RemoteViews(getPackageName(), R.layout.bundle_expanded_notification);

    // Since Lollipop, "reapply()" is used with remote views onto the current one when updating notification.
    // We must clear the view group before adding new content.
    expanded.removeAllViews(R.id.bundle_expanded_container);

    for (final StatusBarNotificationEvo sbn : sbns)
        try {//from   ww w  . j a  va2 s .co m
            expanded.addView(R.id.bundle_expanded_container, sbn.notification().getContentView());
        } catch (final RemoteException ignored) {
        } // Should not happen
    return expanded;
}

From source file:net.pmarks.chromadoze.NoiseService.java

private void addButtonToNotification(Notification n) {
    // Create a new RV with a Stop button.
    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.notification_with_stop_button);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            newStopIntent(this, R.string.stop_reason_notification), PendingIntent.FLAG_CANCEL_CURRENT);
    rv.setOnClickPendingIntent(R.id.stop_button, pendingIntent);

    // Pre-render the original RV, and copy some of the colors.
    final View inflated = n.contentView.apply(this, new FrameLayout(this));
    final TextView titleText = findTextView(inflated, getString(R.string.app_name));
    final TextView defaultText = findTextView(inflated, getString(R.string.notification_text));
    rv.setInt(R.id.divider, "setBackgroundColor", defaultText.getTextColors().getDefaultColor());
    rv.setInt(R.id.stop_button_square, "setBackgroundColor", titleText.getTextColors().getDefaultColor());

    // Insert a copy of the original RV into the new one.
    rv.addView(R.id.notification_insert, n.contentView.clone());

    // Splice everything back into the original's root view.
    int id = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    n.contentView.removeAllViews(id);/*from  w ww  .  j av a 2  s. co  m*/
    n.contentView.addView(id, rv);
}

From source file:org.chromium.chrome.browser.notifications.CustomNotificationBuilder.java

@Override
public Notification build() {
    RemoteViews compactView = new RemoteViews(mContext.getPackageName(), R.layout.web_notification);
    RemoteViews bigView = new RemoteViews(mContext.getPackageName(), R.layout.web_notification_big);

    String time = DateFormat.getTimeFormat(mContext).format(new Date());
    for (RemoteViews view : new RemoteViews[] { compactView, bigView }) {
        view.setTextViewText(R.id.time, time);
        view.setTextViewText(R.id.title, mTitle);
        view.setTextViewText(R.id.body, mBody);
        view.setTextViewText(R.id.origin, mOrigin);
        view.setImageViewBitmap(R.id.icon, mLargeIcon);
    }/*from w w w.j  a v a  2s.  c  om*/

    if (!mActions.isEmpty()) {
        bigView.setViewVisibility(R.id.button_divider, View.VISIBLE);
        bigView.setViewVisibility(R.id.buttons, View.VISIBLE);
        for (Action action : mActions) {
            RemoteViews button = new RemoteViews(mContext.getPackageName(), R.layout.web_notification_button);
            button.setTextViewCompoundDrawablesRelative(R.id.button, action.getIcon(), 0, 0, 0);
            button.setTextViewText(R.id.button, action.getTitle());
            button.setOnClickPendingIntent(R.id.button, action.getActionIntent());
            bigView.addView(R.id.buttons, button);
        }
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
    builder.setTicker(mTickerText);
    builder.setSmallIcon(mSmallIconId);
    builder.setContentIntent(mContentIntent);
    builder.setDeleteIntent(mDeleteIntent);
    builder.setDefaults(mDefaults);
    builder.setVibrate(mVibratePattern);
    builder.setContent(compactView);

    Notification notification = builder.build();
    notification.bigContentView = bigView;
    return notification;
}

From source file:net.hyx.app.volumenotification.factory.NotificationFactory.java

private RemoteViews getCustomContentView() {
    RemoteViews view = new RemoteViews(_package, R.layout.view_layout_notification);
    int style = settings.getResources().getIdentifier("style_" + settings.getTheme(), "style", _package);
    int backgroundColor;
    int iconColor;

    if (style != 0) {
        backgroundColor = settings.getStyleAttributeColor(style, android.R.attr.colorBackground);
        iconColor = settings.getStyleAttributeColor(style, android.R.attr.colorForeground);
    } else {// ww w .  j a  v  a  2s. com
        backgroundColor = settings.getColor(settings.getCustomThemeBackgroundColor());
        iconColor = settings.getColor(settings.getCustomThemeIconColor());
    }
    if (settings.getTranslucent()) {
        backgroundColor = android.R.color.transparent;
    }
    view.setInt(R.id.notification_layout, "setBackgroundColor", backgroundColor);
    view.removeAllViews(R.id.volume_control_wrapper);

    for (int pos = 0; pos < items.size(); pos++) {
        VolumeControl item = model.parseItem(items.get(pos));
        if (item.status == 0) {
            continue;
        }
        RemoteViews btn = new RemoteViews(_package, R.layout.view_widget_volume_control);
        PendingIntent event = PendingIntent.getBroadcast(context.getApplicationContext(), item.id,
                new Intent(context, SetVolumeReceiver.class).putExtra(EXTRA_ITEM_ID, item.id),
                PendingIntent.FLAG_UPDATE_CURRENT);

        btn.setOnClickPendingIntent(R.id.btn_volume_control, event);
        btn.setInt(R.id.btn_volume_control, "setImageResource", model.getIconDrawable(item.icon));
        btn.setInt(R.id.btn_volume_control, "setColorFilter", iconColor);
        view.addView(R.id.volume_control_wrapper, btn);
    }

    return view;
}

From source file:eu.power_switch.widget.activity.ConfigureReceiverWidgetActivity.java

private void saveCurrentConfiguration() {
    try {//  ww  w.  ja  va  2 s. c o m
        // First, get the App Widget ID from the Intent that launched the Activity:
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
            int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            // Perform your App Widget configuration:
            Apartment selectedApartment = getSelectedApartment();
            Room selectedRoom = selectedApartment.getRoom(spinnerRoom.getSelectedItem().toString());
            Receiver selectedReceiver = selectedRoom.getReceiver(spinnerReceiver.getSelectedItem().toString());

            // save new widget data to database
            ReceiverWidget receiverWidget = new ReceiverWidget(appWidgetId, selectedRoom.getId(),
                    selectedReceiver.getId());
            DatabaseHandler.addReceiverWidget(receiverWidget);
            // When the configuration is complete, get an instance of
            // the AppWidgetManager by calling getInstance(Context):
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(ConfigureReceiverWidgetActivity.this);
            // Update the App Widget with a RemoteViews layout by
            // calling updateAppWidget(int, RemoteViews):
            RemoteViews remoteViews = new RemoteViews(getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                    R.layout.widget_receiver);

            LinkedList<Button> buttons = selectedReceiver.getButtons();

            remoteViews.setTextViewText(R.id.textView_receiver_widget_name, selectedApartment.getName() + ": "
                    + selectedRoom.getName() + ": " + selectedReceiver.getName());

            int buttonOffset = 0;
            for (Button button : buttons) {
                // set button action
                RemoteViews buttonView = new RemoteViews(
                        getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                        R.layout.widget_receiver_button_layout);
                SpannableString s = new SpannableString(button.getName());
                s.setSpan(new StyleSpan(Typeface.BOLD), 0, button.getName().length(), 0);
                buttonView.setTextViewText(R.id.button_widget_universal, s);

                if (SmartphonePreferencesHandler.getHighlightLastActivatedButton()
                        && selectedReceiver.getLastActivatedButtonId().equals(button.getId())) {
                    buttonView.setTextColor(R.id.button_widget_universal,
                            ContextCompat.getColor(getApplicationContext(), R.color.color_light_blue_a700));
                }

                PendingIntent pendingIntent = WidgetIntentReceiver.buildReceiverWidgetActionPendingIntent(
                        getApplicationContext(), selectedApartment, selectedRoom, selectedReceiver, button,
                        appWidgetId * 15 + buttonOffset);

                buttonView.setOnClickPendingIntent(R.id.button_widget_universal, pendingIntent);

                remoteViews.addView(R.id.linearlayout_receiver_widget, buttonView);
                buttonOffset++;
            }

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

            // Finally, create the return Intent, set it with the
            // Activity result, and finish the Activity:
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    } catch (Exception e) {
        StatusMessageHandler.showErrorMessage(this, e);
    }
}

From source file:net.hyx.app.volumenotification.NotificationFactory.java

private RemoteViews getCustomContentView() {

    RemoteViews view = new RemoteViews(_package, R.layout.view_layout_notification);
    List<Integer> buttons = new ArrayList<>();
    int theme = resources.getIdentifier("style_" + settings.getTheme(), "style", _package);
    int background_color;
    int icon_color;

    if (theme != 0) {
        TypedArray attrs = context.obtainStyledAttributes(theme, R.styleable.styleable);
        background_color = attrs.getColor(R.styleable.styleable_background_color, 0);
        icon_color = attrs.getColor(R.styleable.styleable_icon_color, 0);
        attrs.recycle();/*from   w ww.j a  va2s .c  o m*/
    } else {
        background_color = settings.getColor(settings.getCustomThemeBackgroundColor());
        icon_color = settings.getColor(settings.getCustomThemeIconColor());
    }
    if (settings.getTransparent()) {
        background_color = android.R.color.transparent;
    }
    view.setInt(R.id.layout_background, "setBackgroundColor", background_color);
    view.removeAllViews(R.id.layout_buttons);

    for (int pos = 1; pos <= BUTTONS_SELECTION_SIZE; pos++) {
        int sel = settings.getButtonSelection(pos);
        if (!settings.getButtonChecked(pos) || buttons.contains(sel) || sel >= BUTTONS_SELECTION_SIZE) {
            continue;
        }
        buttons.add(sel);
        int btn_sel = sel + 1;
        int btn_id = resources.getIdentifier("btn_sel_" + btn_sel, "id", _package);
        RemoteViews btn = new RemoteViews(_package,
                resources.getIdentifier("view_btn_sel_" + btn_sel, "layout", _package));
        Intent intent = new Intent(context, ReceiverSetVolume.class).putExtra("position", pos);
        PendingIntent event = PendingIntent.getBroadcast(context, btn_id, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        btn.setOnClickPendingIntent(btn_id, event);
        //btn.setInt(btn_id, "setImageResource", settings.getDrawable(context, R.array.pref_buttons_icons_entries, settings.getButtonIcon(pos)));
        btn.setInt(btn_id, "setColorFilter", icon_color);
        view.addView(R.id.layout_buttons, btn);
    }
    return view;
}

From source file:io.teak.sdk.NotificationBuilder.java

public static Notification createNativeNotification(final Context context, Bundle bundle,
        TeakNotification teakNotificaton) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Rich text message
    Spanned richMessageText = Html.fromHtml(teakNotificaton.message);

    // Configure notification behavior
    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    builder.setDefaults(NotificationCompat.DEFAULT_ALL);
    builder.setOnlyAlertOnce(true);//  w  w w  .  j av  a2  s .c om
    builder.setAutoCancel(true);
    builder.setTicker(richMessageText);

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    Random rng = new Random();

    // Create intent to fire if/when notification is cleared
    Intent pushClearedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_CLEARED_INTENT_ACTION_SUFFIX);
    pushClearedIntent.putExtras(bundle);
    PendingIntent pushClearedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(),
            pushClearedIntent, PendingIntent.FLAG_ONE_SHOT);
    builder.setDeleteIntent(pushClearedPendingIntent);

    // Create intent to fire if/when notification is opened, attach bundle info
    Intent pushOpenedIntent = new Intent(
            context.getPackageName() + TeakNotification.TEAK_NOTIFICATION_OPENED_INTENT_ACTION_SUFFIX);
    pushOpenedIntent.putExtras(bundle);
    PendingIntent pushOpenedPendingIntent = PendingIntent.getBroadcast(context, rng.nextInt(), pushOpenedIntent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentIntent(pushOpenedPendingIntent);

    // Because we can't be certain that the R class will line up with what is at SDK build time
    // like in the case of Unity et. al.
    class IdHelper {
        public int id(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "id", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.id." + identifier);
            }
            return ret;
        }

        public int layout(String identifier) {
            int ret = context.getResources().getIdentifier(identifier, "layout", context.getPackageName());
            if (ret == 0) {
                throw new Resources.NotFoundException("Could not find R.layout." + identifier);
            }
            return ret;
        }
    }
    IdHelper R = new IdHelper(); // Declaring local as 'R' ensures we don't accidentally use the other R

    // Configure notification small view
    RemoteViews smallView = new RemoteViews(context.getPackageName(),
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_notif_no_title_v21")
                    : R.layout("teak_notif_no_title"));

    // Set small view image
    try {
        PackageManager pm = context.getPackageManager();
        ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0);
        smallView.setImageViewResource(R.id("left_image"), ai.icon);
        builder.setSmallIcon(ai.icon);
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to load icon resource for Notification.");
        return null;
    }

    // Set small view text
    smallView.setTextViewText(R.id("text"), richMessageText);

    // Check for Jellybean (API 16, 4.1)+ for expanded view
    RemoteViews bigView = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && teakNotificaton.longText != null
            && !teakNotificaton.longText.isEmpty()) {
        bigView = new RemoteViews(context.getPackageName(),
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? R.layout("teak_big_notif_image_text_v21")
                        : R.layout("teak_big_notif_image_text"));

        // Set big view text
        bigView.setTextViewText(R.id("text"), Html.fromHtml(teakNotificaton.longText));

        URI imageAssetA = null;
        try {
            imageAssetA = new URI(teakNotificaton.imageAssetA);
        } catch (Exception ignored) {
        }

        Bitmap topImageBitmap = null;
        if (imageAssetA != null) {
            try {
                URL aURL = new URL(imageAssetA.toString());
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                topImageBitmap = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap == null) {
            try {
                InputStream istr = context.getAssets().open("teak_notif_large_image_default.png");
                topImageBitmap = BitmapFactory.decodeStream(istr);
            } catch (Exception ignored) {
            }
        }

        if (topImageBitmap != null) {
            // Set large bitmap
            bigView.setImageViewBitmap(R.id("top_image"), topImageBitmap);
        } else {
            Log.e(LOG_TAG, "Unable to load image asset for Notification.");
            // Hide pulldown
            smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
        }
    } else {
        // Hide pulldown
        smallView.setViewVisibility(R.id("pulldown_layout"), View.INVISIBLE);
    }

    // Voodoo from http://stackoverflow.com/questions/28169474/notification-background-in-android-lollipop-is-white-can-we-change-it
    int topId = Resources.getSystem().getIdentifier("status_bar_latest_event_content", "id", "android");
    int topBigLayout = Resources.getSystem().getIdentifier("notification_template_material_big_media_narrow",
            "layout", "android");
    int topSmallLayout = Resources.getSystem().getIdentifier("notification_template_material_media", "layout",
            "android");

    RemoteViews topBigView = null;
    if (bigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // This is invisible inner view - to have media_actions in hierarchy
        RemoteViews innerTopView = new RemoteViews("android", topBigLayout);
        bigView.addView(android.R.id.empty, innerTopView);

        // This should be on top - we need status_bar_latest_event_content as top layout
        topBigView = new RemoteViews("android", topBigLayout);
        topBigView.removeAllViews(topId);
        topBigView.addView(topId, bigView);
    } else if (bigView != null) {
        topBigView = bigView;
    }

    // This should be on top - we need status_bar_latest_event_content as top layout
    RemoteViews topSmallView;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        topSmallView = new RemoteViews("android", topSmallLayout);
        topSmallView.removeAllViews(topId);
        topSmallView.addView(topId, smallView);
    } else {
        topSmallView = smallView;
    }

    builder.setContent(topSmallView);

    Notification n = builder.build();
    if (topBigView != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // Use reflection to avoid compile-time issues, we check minimum API version above
        try {
            Field bigContentViewField = n.getClass().getField("bigContentView");
            bigContentViewField.set(n, topBigView);
        } catch (Exception ignored) {
        }
    }

    return n;
}