I have problem with the back button in action bar to fragment
my code fragment:
public class Server extends Fragment {
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_server, container, false);
Button server = (Button) view.findViewById(R.id.status);
/** Button Check Status Server **/
server.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(view.getContext(), ServerStatus.class);
startActivityForResult(myIntent, 0);
getActivity().finish();
}
});
return view;
}
}
my code in activity:
public class ServerStatus extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_status);
}
}
My code in Fragment
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch (position) {
case 0:
objFragment = new Account();
break;
case 1:
objFragment = new AllNews();
break;
case 2:
objFragment = new Server();
break;
case 3:
objFragment = new Account();
break;
case 4:
objFragment = new Account();
break;
case 5:
objFragment = new Account();
break;
case 6:
objFragment = new About();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container,objFragment)
.commit();
}
Every time I click the back button, the program always closes. I already tried to use:
getActionBar().setDisplayHomeAsUpEnabled(true);
and this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
Can anyone help me to fix my program?
EDIT: Concerning cross-activity-navigation, you should not use startActivityForResult() in that way. Try to use startActivity() instead. If you start an activity for a result, the calling activity waits for the onActivityResult() callback and should not be finished.
In the manifest file you should declare the fragment's activity as parent activity of ServerStatus to enable back navigation. You should not need NavUtils.
If you want to enable fragment navigation within an activity, you have to add your fragment transactions to the backstack:
getFragmentManager().beginTransaction().addToBackStack(null).replace(...).commit();
Then you have to call getFragmentManager().popBackStack() in onOptionsItemSelected() to enable back navigation for the action bar:
#override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
You may have to override onBackPressed() to enable back navigation for the back button:
#override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() >= 1) {
getFragmentManager().popBackStack(); // return to previous fragment
}
else {
super.onBackPressed(); // Exit application when no fragment is on the backstack
}
}
Related
I have ,
Two fragments (Fragment1,Fragment2).
Two buttons (Btn1 in frag1 , Btn2 in frag2).
A bottom navigation view.
On clicking the Btn in frag1 , we will be directed to frag2.
On clicking the Btn in frag2 , we will be directed to frag1.
while directing from frag(1->2 or 2->1), the icon on the bottom navigation view stays the same
Is there a way to highlight that icon with respect to the loaded fragment?
On Click Listener for btn in frag1
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment2()).commit();
On Click Listener for btn in frag2
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment1()).commit();
OnItemSelectedListener for bottom nav in MainActivity Code
((BottomNavigationView)findViewById(R.id.bottom_nav)).setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener(){
Fragment clickedFragment = null;
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.one: clickedFragment = new Fragment1(); break;
case R.id.two: clickedFragment = new Fragment2(); break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.body_container, clickedFragment).commit();
return true;
}
});
The setOnItemSelectedListener is only triggered whenever the selected item of the BottomNavigationView changes. What you are currently doing is changing the current displayed fragment. Instead of changing the fragment, you should set the selected item of the BottomNavigationView instead. Something like this should work
((BottomNavigationView) findViewById(R.id.bottom_nav)).setSelectedItemId(R.id.your_menu_item_id);
Create a class temp in the same package as the main activity is in and add the below field to it.
public static BottomNavigationView bottomNavigationView;
Just go through the code, I explained in comments.
Main Activity Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavView = temp.bottomNavigationView = findViewById(R.id.bottom_nav);
//This line, initially when the app is opened, displays the fragment1 by default
getSupportFragmentManager().beginTransaction().replace(R.id.body_container, new Fragment1()).commit();
bottomNavView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment clickedFragment = null;
switch (item.getItemId()) {
case R.id.one: clickedFragment = new Fragment1(); break;
case R.id.two: clickedFragment = new Fragment2(); break;
}
//This line replaces the fragment when user clicks on icon of bottom navigation view
getSupportFragmentManager().beginTransaction().replace(R.id.body_container, clickedFragment).commit();
return true;
}
});
}
3.OnViewCreated in Fragment1
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.btn_to_frag2).setOnClickListener(l->{
temp.bottomNavigationView.setSelectedItemId(R.id.two);
});
}
4.OnViewCreated in Fragment2
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.btn_to_frag1).setOnClickListener(l->{
temp.bottomNavigationView.setSelectedItemId(R.id.one);
});
}
Just make sure that the setOnItemSelectedListener has a return value of true
It works fine without setting the setSelectedItemId
I have the following bottom navbar code to switch between 3 fragments:
public class MainActivity extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
fragment = new NotificationsFragment();
break;
}
return loadFragment(fragment);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
}
In the fragments there are RecyclerViews with lists. Every time I switch between the tabs (between fragments), it looks like the fragment is reloaded, and the lists jump to the top. I want to prevent that reloading so that the user stays on the same place in the list he viewed before switching fragments
The problem is that you are creating a new instance every time. You can cache the instance like:
private Fragment mHomeFragment = new HomeFragment();
private Fragment mDashboardFragment = new DashboardFragment();
private Fragment mNotificationsFragment = new NotificationsFragment();
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = mHomeFragment;
break;
case R.id.navigation_dashboard:
fragment = mDashboardFragment;
break;
case R.id.navigation_notifications:
fragment = mNotificationsFragment;
break;
}
return loadFragment(fragment);
}
As we could see, you are always replace your fragment when clicks on bottom navigation, replace means previous fragment removes and state cleans. The solution is do not create your fragment each time and use attach/detach method for showing actual fragment. Here is already described about these methods.
I am trying to create Navigation View in Bottom App bar in Activity but android.R.id.home doesn't work . I have set the BottomAppbar object as setSupportActionBar(mBottomAppBar) but doesn't work
mBottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.emp_menu_home:
setFragment(empHomeFragment);
break;
case R.id.emp_menu_notif:
setFragment(notificationsFragment);
break;
case R.id.emp_menu_Inbox:
setFragment(inboxFragment);
break;
case R.id.emp_menu_cv:
setFragment(cvFragment);
break;
case android.R.id.home:
Toast.makeText(Main2Activity.this, "Home is click", Toast.LENGTH_SHORT).show();
NaviDrawerFragment naviDrawerFragment=new NaviDrawerFragment();
naviDrawerFragment.show(getSupportFragmentManager(),naviDrawerFragment.getTag());
break;
default:
return false;
}
return true;
}
});
Try adding: setHasOptionsMenu(true); in your onCreate().
or
If you're using the new Toolbar and ActionbarDrawerToggle. You can assign clickHandler directly. For my activities that have this drawer toolbar I implemented an interface to enable drawer if at root,
#Override
public void enableDrawer(boolean enable) {
mDrawerToggle.setDrawerIndicatorEnabled(enable);
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Pop fragment back stack or pass in a custom click handler from the fragment.
}
});
}
I have the following Activity code:-
public class legislator_info extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_legislator_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Legislator Info");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
String bioguide = i.getExtras().getString("Person");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
So basically I have a fragment which has a list view displayed in it. On click of a list Item I start this activity and I want to go back to the previous fragment on the back button click. I tried the above code but I am not able to travel back. Am pretty new at this any help is appreciated.
I have added my fragment in the following way:-
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
LegislatorFragment lf = new LegislatorFragment();
ft.replace(R.id.fragment_container,lf);
ft.addToBackStack(null);
ft.commit();
I am still not clear what you want to achieve but you can try this
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
EDIT:
case android.R.id.home:
//call onBackPressed here
onBackPressed();
return true;
You have to override onOptionsItemSelected because you are trying with Action bar's back button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
Then override BackPressed -
#Override
public void onBackPressed()
{
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}
else {
super.onBackPressed();
}
}
I have a Activity named as Wallet and have a Activity named as CRechargeMain which adds two frgament named as "Mobile","Data";what I want in Wallet screen I have a Listview in which in case 0: when I click I want to go to CRechargeMain and show"Mobile" tab and in case 1 : when I click I want to go CRechareMain and open tab " data" .how can I do that
code for wallet:-
m_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mMobileRecharges);
break;
case 1:
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
startActivity(mDataRecharge);
break;
case 2:
Intent m_Earning= new Intent(CMyWalletScreen.this,CWalletTransactionScreen.class);
startActivity(m_Earning);
break;
}
}
});
code for CRechargeMain:-
public class CRechargeMain extends AppCompatActivity {
View m_Main;
private ViewPager m_ViewPager;
private Toolbar m_ToolBar;
private String[]actonBar={"Mobile Recharge","Mobile Data Recharge"};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recharge_main);
init();
}
public void init() {
m_ToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(m_ToolBar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
m_ToolBar.setTitle("Mobile Recharge");
TabLayout m_TabLayout = (TabLayout) findViewById(R.id.tab_layout);// finding Id of tablayout
m_TabLayout.addTab(m_TabLayout.newTab().setText("Mobile"));// add deal listin tab
m_TabLayout.addTab(m_TabLayout.newTab().setText("Data Card"));// add stories tab
m_TabLayout.setTabGravity(TabLayout.GRAVITY_FILL);// setting Gravity of Tab
m_ViewPager = (ViewPager) findViewById(R.id.pager);//finding Id of ViewPager
CRechargePager m_oMobilePager = new CRechargePager
(getSupportFragmentManager(), m_TabLayout.getTabCount());
m_ViewPager.setAdapter(m_oMobilePager);// adiing adapter to ViewPager
m_ViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(m_TabLayout));// performing action of page changing
m_TabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
m_ViewPager.setCurrentItem(tab.getPosition());
m_ToolBar.setTitle(actonBar[tab.getPosition()]);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_wallet, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use the same intent and select tab based on the intent argument in your activity.
As my assumption you are having two activity, activity1 contains list and activity2 contains fragments.from activity1 based on conditions you have to jump to activity2 (fragments).Just call as below
Intent i =New Intent(this,CRechargeMain.class);
i.putExtra("",0);
startActivity(i);
In Activty2 on create method based on conditions you have to set fragment to load.
FragmentManager FM = getFragmentManager();
FM.beginTransaction().replace(R.id.content_frame, detail).commit();
Intent mMobileRecharges = new Intent(CMyWalletScreen.this,CRechargeMain.class);
intent.putExtra("doWhat", 0);
Intent mDataRecharge = new Intent(CMyWalletScreen.this,CRechargeMain.class);
intent.putExtra("doWhat", 1);
In your receiving activity:
int iDoWhat = intent.getIntExtra("doWhat", -1);
Then make your decision based on the value of iDoWhat.
int iDoWhat = getIntent().getIntExtra("doWhat",-1);
switch (iDoWhat) {
case -1:
//select tab 0
break;
case 0:
//select tab 0
break;
case 1:
//select tab 1
break;
}
You have to write the code for selecting the tab now you know which one.