1
我創建一個自定義通知,並使用此代碼動態添加按鈕Dyanamically中添加自定義通知RemoteViews在for循環,問題:在設定的PendingIntent
RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.custom_notification);
for (int i = 0; i < 100; i++) {
Intent mybuttonsIntent = new Intent(this, NotifyActivityHandler.class);
RemoteViews rv = new RemoteViews(this.getPackageName(), R.layout.button_layout);
Bundle b = new Bundle();
b.putInt("abcd", i);
mybuttonsIntent.putExtras(b);
rv.setOnClickPendingIntent(R.id.button, PendingIntent.getActivity(this, 0, mybuttonsIntent, PendingIntent.FLAG_UPDATE_CURRENT));
remoteViews.addView(R.id.rlMainNotification, rv);
}
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setContent(remoteViews);
NotificationManager notificationmanager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationmanager.notify(0, builder.build());
這裏的button_layout.xml:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/button"
android:layout_height="wrap_content"
android:layout_weight="1" />
在NotifyActivityHandler中,我使用此代碼來獲取Int:
Bundle extras = getIntent().getExtras();
if (extras != null) {
int level = extras.getInt("abcd");
Toast.makeText(this, "testing" + level, Toast.LENGTH_LONG).show();
但問題是每個按鈕都通過相同的Int,即如果不使用R.id.button,我使用rv.getLayoutId(),則按鈕不響應。我希望每個按鈕都應該分別在for循環中傳遞分配給它的值。
編輯:在評論者的要求,這裏的custom_notification的XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="10">
<LinearLayout
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent">
<ImageView
android:id="@+id/autoIcon"
android:tint="@color/themeColor"
android:layout_gravity="center"
android:scaleType="fitCenter"
android:src="@drawable/ic_brightness_medium_white_48dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
</LinearLayout>
<LinearLayout
android:id="@+id/rlMainNotification"
android:layout_width="0dp"
android:gravity="center_vertical"
android:layout_gravity="center_vertical"
android:orientation="horizontal"
android:layout_height="match_parent"
android:paddingRight="4dp"
android:paddingLeft="2dp"
android:layout_weight="9"
>
</LinearLayout>
</LinearLayout>
rlMainNotification在哪裏定義?我試圖完成類似的事情,但不成功。你介意張貼布局XML爲custom_notification以及 –
這是一個線性佈局在custom_notification.xml – Usman
我也已經添加了XML請求。 – Usman