我想在新的androidx的默认操作栏中有一个Backbutton jetpack导航应用程序。
我按照google navigation-getting-started来构建导航应用程序,但是我在操作栏中缺少后退按钮,所以我在MainActivity的OnCreate中添加了一个内容:
ActionBar actionbar = getSupportActionBar();
NavController nc = Navigation.findNavController(mainFragment.getView());
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(nc.getGraph()).build();
androidx.navigation.ui.NavigationUI.setupActionBarWithNavController(this,nc, appBarConfiguration);
现在,如果我不在开始主片段中,那么我会在ActionBar中看到一个Backbutton,但是如果我点击该按钮,则没有back功能。常规后退键可以正常工作,但是如何使操作栏后退按钮正常工作。
更新:从第二个片段到第一个(主/根)片段不起作用。从第三到第二个片段它正在工作。 nav-graph
答案 0 :(得分:1)
尝试:-
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do your stuff here
}
});
第二个选项是;-
@Override
public boolean onSupportNavigateUp() {
return super.onSupportNavigateUp();
// do your stuff here
}
答案 1 :(得分:0)
package com.pg.navigation;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NavUtils;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements main_fragment.OnFragmentInteractionListener, Fragment2.OnFragmentInteractionListener, fragment3.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment mainFragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
ActionBar actionbar = getSupportActionBar();
NavController nc = Navigation.findNavController(mainFragment.getView());
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(nc.getGraph()).build();
androidx.navigation.ui.NavigationUI.setupActionBarWithNavController(this,nc, appBarConfiguration);
}
@Override
public boolean onSupportNavigateUp() {
return super.onSupportNavigateUp();
}
@Override
public void onFragmentInteraction(Uri uri) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}