我使用以下代码创建自定义通知并动态添加按钮:
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即99
如果不是使用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>
最佳答案
将此行更改为:
rv.setOnClickPendingIntent(R.id.button, PendingIntent.getActivity(this, 0, mybuttonsIntent, PendingIntent.FLAG_UPDATE_CURRENT));
至
rv.setOnClickPendingIntent(R.id.button, PendingIntent.getActivity(this, i, mybuttonsIntent, PendingIntent.FLAG_UPDATE_CURRENT));
基本上将0更改为i。