我正在学习 android,我面临着一个不知道如何解决它的挑战。那是我无法回到开始活动的片段。我正在从片段打开第二个活动,但是当我在第二个活动上按下后退按钮时,它不会导航到打开该活动的片段,而是显示主页片段。我试过 this 但没有成功。
这是打开第二个片段的聊天片段
这是第二个活动,如果我按下后退按钮不会转到聊天片段
当我按下第二个活动的后退按钮时,这就是我得到的。显示首页片段内容
这是我的主要活动
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
Toolbar toolbar;
TextView title,txt_profile_contact,txt_profile_name;
ActionBarDrawerToggle toggle;
DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationRepository=new NotificationRepository(this);
toolbar=findViewById(R.id.toolbar);
title=toolbar.findViewById(R.id.tool_bar_title);
title.setText(R.string.home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
drawer= findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
assert drawer != null;
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
}
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
doExit(false);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment=null;
int idd=R.id.main_fragment_main;
if (id == R.id.menu_chat)
{
title.setText("Chat");
fragment=new ChatFragment();
} else (id == R.id.menu_home) {
title.setText("Home");
fragment=new HomeFragment();
Utils.setIsOnChatActivity(this,false);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
load_fragment(fragment);
return true;
}
private void load_fragment(Fragment fragment)
{
if(fragment==null)
{
return;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.fadein, R.anim.fadeout);
toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.white));
toolbar.setBackgroundResource(R.color.colorPrimary);
title.setTextColor(getResources().getColor(R.color.white));
try {
ft.replace(R.id.main_fragment, fragment)
.addToBackStack(null)
.commit();
} catch (IllegalStateException e) {
//ExceptionHandler.logException(e);
}
}
}
这是聊天片段
public class ChatFragment extends Fragment implements TutorListAdapter.TutorOnclickListener{
private static final String TAG = ChatFragment.class.getSimpleName();
public ChatFragment() {
// Required empty public constructor
}
FloatingActionButton actionButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_chat, container, false);
actionButton=view.findViewById(R.id.new_chat_list_btn);
actionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getActivity(),SecondActivity.class);
startActivity(intent);
mActivity.overridePendingTransition(R.anim.fadein, R.anim.fade_out);
}
});
return view;
}
}
这是我的第二个活动。注意,我什至尝试过注释代码,但不起作用
public class SecondActivity extends AppCompatActivity {
Toolbar toolbar;
TextView barText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_details);
toolbar=findViewById(R.id.custom_tool_bar);
barText=toolbar.findViewById(R.id.toolbar_title);
barText.setText("My Activity");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// onBackPressed();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public void onBackPressed() {
// Toast.makeText(this, "back pressed?", Toast.LENGTH_SHORT).show();
// if ( getFragmentManager().getBackStackEntryCount() > 0)
// {
// getFragmentManager().popBackStack();
// return;
// }
// super.onBackPressed();
// }
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
}
答案 0 :(得分:0)
第 1 步:创建一个自定义 ViewModelFactory
,它基本上是一个 Singleton
类。这个类提供ViewModel
。
CustomViewModelProvider.java
public class CommonViewModelProvider extends ViewModelProvider.NewInstanceFactory {
private static CommonViewModelProvider commonViewModelProvider;
private final BottomNavigationViewModel bottomNavigationViewModel;
CommonViewModelProvider(){
bottomNavigationViewModel = new BottomNavigationViewModel();
}
public static CommonViewModelProvider getInstance(){
if (commonViewModelProvider == null)
commonViewModelProvider = new CommonViewModelProvider();
return commonViewModelProvider;
}
@NotNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass){
return (T) bottomNavigationViewModel;
}
}
BottomNavigationViewModel.java
public class BottomNavigationViewModel extends ViewModel {
private final MutableLiveData<Integer> currentFragmentId;
public Integer getCurrentFragmentId(){
return currentFragmentId.getValue();
}
public void setCurrentFragmentId(int currFragmentId){
currentFragmentId.setValue(currFragmentId);
}
public BottomNavigationViewModel(){
currentFragmentId = new MutableLiveData<>();
// R.id.navigation_snap is my first fragment. You should replace with your FirstFragment i.e HomeFragment
currentFragmentId.setValue(R.id.navigation_snap);
}
}
第 2 步:
您将有一个 BottomNavigationActivity
,其中包含 3 个 fragments
。第三个是您的 ChatFragment
。在此活动中,我从 fragment
获取当前 BottomNavigationViewModel
并将其设置为 BottomNavigationView
,如 navView.setSelectedItemId(currentFragment);
。这样当您从 SecondActivity
返回到 BottomNavigationActivity
时,将显示 ChatFragment
而不是 HomeFragment
。
BottomNavigationActivity.java
public class BottomNavigationActivity extends AppCompatActivity {
BottomNavigationViewModel bottomNavigationViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
//bottomNavigationViewModel = new ViewModelProvider(this).get(BottomNavigationViewModel.class);
CommonViewModelProvider commonViewModelProvider = CommonViewModelProvider.getInstance();
bottomNavigationViewModel = commonViewModelProvider.create(BottomNavigationViewModel.class);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_snap, R.id.navigation_home, R.id.navigation_chat)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
Integer currentFragment = bottomNavigationViewModel.getCurrentFragmentId();
navView.setSelectedItemId(currentFragment);
}
}
第 3 步:
现在您想从 SecondActivity
打开 ChatFragment
。那么,在 SecondActivity
中只需更新 currentFragmentId
的 BottomNavigationViewModel
变量,这样当您按下back
按钮时,这个 currentFragment
将显示在 BottomNavigationActivity
.
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
CommonViewModelProvider commonViewModelProvider = CommonViewModelProvider.getInstance();
BottomNavigationViewModel bottomNavigationViewModel = commonViewModelProvider.create(BottomNavigationViewModel.class); Log.d("tisha==>>","View Model ID inside Second Activity"+ bottomNavigationViewModel.hashCode());
bottomNavigationViewModel.setCurrentFragmentId(R.id.navigation_chat);
}
}
注意:每当您想打开 BottonNavigationActivity
时,请确保您已设置正确的 fragment
,它将首先打开。使用以下代码将 currentFragment
设置为 ViewModel
,这已在 SecondActivity
中完成。
CommonViewModelProvider commonViewModelProvider = CommonViewModelProvider.getInstance();
BottomNavigationViewModel bottomNavigationViewModel = commonViewModelProvider.create(BottomNavigationViewModel.class); Log.d("tisha==>>","View Model ID inside Second Activity"+ bottomNavigationViewModel.hashCode());
bottomNavigationViewModel.setCurrentFragmentId(R.id.navigation_chat);