在ActionbarDrawerToggle中设置退格键来导航到之前的片段,可以通过以下步骤实现:
以下是一个示例代码:
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.abc_action_bar_up_description);
drawerLayout.addDrawerListener(drawerToggle);
fragmentManager = getSupportFragmentManager();
if (savedInstanceState == null) {
// 初始化显示的Fragment
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, new HomeFragment());
transaction.commit();
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == android.R.id.home) {
// 退格键被选中
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
这样,当用户点击退格键时,将会从FragmentManager的回退栈中弹出当前的Fragment,返回到之前的片段。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云