如何在Android通知中添加按钮

时间:2011-06-02 15:23:56

标签: android android-layout notifications

我正在尝试在每个通知中添加一个按钮...用户可以单击按钮删除个别通知,我看到很多人说只是参考“创建自定义扩展视图”并使用RemoteViews,但它是否可能修改官方代码并让按钮工作? 我使用imagebutton

在“status_bar_latest_event_context.xml”中添加了按钮
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingTop="3dp"
    >
    <!--com.android.server.status.AnimatedImageView android:id="@+id/icon" -->
    <ImageView android:id="@+id/icon"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:scaleType="fitCenter"
        android:src="@drawable/arrow_down_float"/>
    <TextView android:id="@+id/title"
        android:textAppearance="@style/TextAppearance.StatusBar.EventContent.Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:paddingLeft="4dp"
        />
     <ImageButton android:id="@+id/imgbtn_del" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/btn_close"/>

</LinearLayout>

它将在每个通知中显示图像按钮,但我不知道如何让按钮工作。

在StatusBarService.java中,我们可以找到

    // bind the click event to the content area
    ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
    content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
    content.setOnFocusChangeListener(mFocusChangeListener);
    PendingIntent contentIntent = n.contentIntent;
    if (contentIntent != null) {
        content.setOnClickListener(new Launcher(contentIntent, notification.pkg,
                    notification.tag, notification.id));
    }

它将click事件绑定到内容区域。所以我无法点击按钮。 我不知道如何修改源代码以及如何设置OnClick函数..

请帮忙...... 非常感谢!

1 个答案:

答案 0 :(得分:0)

我希望这可以帮助你

//Exemple of notification with Button
private static void scheduleNotificationWithButton(Context context, String message) {

    int notifReCode = 1;

    //What happen when you will click on button
    Intent intent = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_ONE_SHOT);

    //Button
    NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.my_image, "Delete", pendingIntent).build();

    //Notification
    Notification notification = new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Back to Application ?")
            .setContentTitle("Amazing news")
            .addAction(action) //add buton
            .build();

    //Send notification
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);
}