【问题标题】:Switch navigation tabs manually in Navigation drawer in Android在 Android 的导航抽屉中手动切换导航选项卡
【发布时间】:2015-04-01 20:40:21
【问题描述】:
我在我的应用程序中使用最新的 Lollipop 风格的导航抽屉。有关更多信息,请参阅 this example。我使用片段来显示不同的导航选项卡。现在,当我从 android 设备的通知栏中单击某个通知时,我需要打开,比如说抽屉中的第 5 项。我被困在如何通过单击通知直接切换到该片段。我非常清楚如何使用 Activity 来做到这一点。谁能给我建议任何解决方案?
提前致谢。
已解决:
我已经按照 Ziem 的回答解决了这个问题。我刚刚添加了以下几行以将其作为新屏幕打开并清除旧的活动堆栈:
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
【问题讨论】:
标签:
android
android-fragments
navigation-drawer
navigationbar
【解决方案1】:
您可以将PendingIntent 添加到通知的click:
PendingIntent resultPendingIntent;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
...
.setContentIntent(resultPendingIntent);
接下来,您需要在 Activity 中处理通知的 Intent。
例子:
// How to create notification with Intent:
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("open", 1);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setContentIntent(resultPendingIntent);
int mNotificationId = 33;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
//How to handle notification's Intent:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getIntent() != null && getIntent().hasExtra("open")) {
int fragmentIndexToOpen = getIntent().getIntExtra("open", -1)
// show your fragment
}
}
}