The new fragment which is displayed on a button click is not closing after pressing the back button,instead it is closing the whole application. The button is present inside one of the three tabs. The code of the mainActivity.java, HeroesFragment(the fragment having the three tabs),StrengthHeroesFragment(one of the three tab having the button) is mentioned below.
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer=findViewById(R.id.draw_layout);
NavigationView navigationView=findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawer,toolbar,
R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState==null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new HeroesFragment()).commit();
navigationView.setCheckedItem(R.id.nav_heroes);}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_heroes:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new HeroesFragment()).commit();
break;
case R.id.nav_items:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new ItemsFragment()).commit();
break;
case R.id.nav_counterpicker:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new CounterPickerFragment()).commit();
break;
case R.id.nav_news:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new NewsFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
}
HeroesFragment.java (The fragment containing the three tabs)
public class HeroesFragment extends Fragment {
private TabLayout tabLayout;
private AppBarLayout appBarLayout;
private ViewPager viewPager;
View view;
RelativeLayout relativeLayout;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.fragment_heroes,container,false);
relativeLayout=(RelativeLayout)view.findViewById(R.id.hero_layout);
tabLayout=(TabLayout)view.findViewById(R.id.heroes_tablayout);
appBarLayout=(AppBarLayout)view.findViewById(R.id.hero_appbar);
viewPager=(ViewPager)view.findViewById(R.id.heroes_viewpager);
ViewPageAdapter adapter=new ViewPageAdapter(getChildFragmentManager(),1);
adapter.AddFragment(new StrengthHeroesFragment(),"Strength" );
adapter.AddFragment(new AgilityHeroesFragment(),"Agility");
adapter.AddFragment(new IntelligenceHeroesFragment(),"Intelligence");
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 0:
Toast.makeText(getContext(),"Tab 1",Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getContext(),"Tab 2",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getContext(),"tab 3",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return view;
}
}
StrengthHeroesFragment.java (the fragment contaning the button )
public class StrengthHeroesFragment extends Fragment {
View view;
ImageButton ib1,ib2,ib3,ib4,ib5,ib6;
TextView t1,t2,t3,t4,t5,t6;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_strength_heroes,container,false);
ib1=(ImageButton)view.findViewById(R.id.abaddon_icon);
ib1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HeroDetailsFragment heroDetailsFragment=new HeroDetailsFragment();
Bundle data=new Bundle();
data.putString("heroname","Abaddon");
heroDetailsFragment.setArguments(data);
FragmentTransaction transaction=getChildFragmentManager().beginTransaction();
transaction.replace(R.id.strength_hero_layout,heroDetailsFragment).addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
When i use getFragmentManager() instead of getChildFragmentManager() in the StrengthHeroes Fragment it actually works but when i switch to another fragments in the navigation drawer, the content in the tab layout fragments is gone.
I also tried using setPrimaryNavigationFragment() it still didn't worked.
Please help me with it.....
Thanks in Advance.
use below code instead of super.onBackpress()
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}
else{
getSupportFragmentManager().popBackStack();
}
}
Related
Need a little help on how to approach saving state in my single activity application. I looked at a few resources but couldn't quite find one that fits the build. Essentially I have single activity with a Fragment container view that I'm using to swap out fragments as needed. My issue is that as my activity is destroyed when a lifecycle event occurs, the fragment with my view pager is restored but the individual fragments on the tabs are not loaded. I cannot figure out how to save the state properly. Below is my code:
Activity:
public class StartActivity extends AppCompatActivity {
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mAuth = FirebaseAuth.getInstance();
if (savedInstanceState == null) {
LoginFragment fragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, fragment)
.commit();
}
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
MainActivity mainActivityFrag = new MainActivity();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, mainActivityFrag)
.commit();
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}
Fragment With View Pager:
public class MainActivity extends Fragment {
private FirebaseAuth mAuth;
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private TabLayout tabs;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = mAuth = FirebaseAuth.getInstance();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
sectionsPagerAdapter = new SectionsPagerAdapter(getContext(),((AppCompatActivity)getActivity()).getSupportFragmentManager());
viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.showContextMenu();
toolbar = view.findViewById(R.id.topAppBar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
tabs.getTabAt(0).setIcon(R.drawable.home_selector);
tabs.getTabAt(1).setIcon(R.drawable.destination);
tabs.getTabAt(2).setIcon(R.drawable.mail_outline_blk);
tabs.getTabAt(3).setIcon(R.drawable.notification_bell);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.logout:
mAuth.signOut();
//navigate to home fragment
LoginFragment fragment = new LoginFragment();
((AppCompatActivity)getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout, fragment)
.commit();
return true;
default:
return false;
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Adapter Code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
PostFragment postFragment = new PostFragment();
return postFragment;
case 1:
TestFragment userFeedFragmentt = new TestFragment();
return userFeedFragmentt;
default:
TestFragment userFeedFragmenttt = new TestFragment();
return userFeedFragmenttt;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 2 total pages.
return 4;
}
}
I have a TabLayout with 3 tabs and a BottonNavigation and I need that at the moment of pressing patients and configuration the tablayout disappears, I do not know what line of code I need?
I also use a ViewPager, everything works well the only thing I need is that the TabLayout disappears when it is in patients. In the Patient Fragment I will use a recycleView and CardView, I want to show the photo of the patient and his data
project image:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
BottomNavigationView mbottomNavigation;
private ViewPager mviewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//bottomNavigation
mbottomNavigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
mbottomNavigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
//aqui se especifica donde es que se quiere que inicie el bottom
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AgendaFragment()).commit();
//ViewPager
mviewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(mviewPager);
final BottomNavigationView navigation=(BottomNavigationView)findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
mviewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position){
case 0:
navigation.setSelectedItemId(R.id.nav_agenda);
break;
case 1:
navigation.setSelectedItemId(R.id.nav_pacientes);
break;
case 2:
navigation.setSelectedItemId(R.id.nav_configuracion);
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private OnNavigationItemSelectedListener navigationItemSelectedListener = new OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_agenda:
mviewPager.setCurrentItem(0);
return true;
case R.id.nav_pacientes:
mviewPager.setCurrentItem(1);
return true;
case R.id.nav_configuracion:
mviewPager.setCurrentItem(2);
return true;
}
return false;
}
};
private void setupViewPager(ViewPager mviewPager) {
BottomNavPagerAdapter adapter=new BottomNavPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new AgendaFragment());
adapter.addFragment(new PacientesFragment());
adapter.addFragment(new ConfiguracionFragment());
mviewPager.setAdapter(adapter);
}
}
PatientsFragment.java:
public class AgendaFragment<toolbar> extends Fragment {
private TabLayout tabLayout;
private ViewPager firstViewPager;
public AgendaFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView=inflater.inflate(R.layout.fragment_agenda,container,false);
firstViewPager=(ViewPager)rootView.findViewById(R.id.viewpager_content);
tabLayout=(TabLayout)rootView.findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(firstViewPager);
setupViewPager(firstViewPager);
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
TabViewPagerAdapter adapter = new TabViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new Tab1Fragment(), "Today");
adapter.addFragment(new Tab1Fragment(), "Tomorrow");
adapter.addFragment(new Tab1Fragment(), "Other Date");
viewPager.setAdapter(adapter);
}
}
You could just keep your activity layout with the BottomNavigation and the FrameLayout to show the content of each navigation item. Add the AppBar with the Toolbar and TabBar in your Agenda Fragment layout.
I have a FloatingActionButton in my android navigation drawer with tablayout which displays the following message :
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homeFragment();
SnackBarMessage("Go To Inbox.");
}
});
using snackbar
public void SnackBarMessage(String message){
Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
let's say I have 3 tabs e.g (tab 0 ,tab 1 , tab 2)
how can I make the Floating action button take me to tab 2 once I click on it
This is the fragment containing the tabs
public class HomeFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager mViewPager;
private OnFragmentInteractionListener mListener;
private SectionsPagerAdapter mSectionsPagerAdapter;
ArrayList<String> tabName;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
mViewPager = (ViewPager)view.findViewById(R.id.container);
tabName=new ArrayList<String>();
int [] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_move_to_inbox,
R.drawable.ic_notifications,
R.drawable.ic_swap_horiz,
R.drawable.ic_people,
};
String[] strings = { "Main Page Goes Here", "Messages Go Here", "Notifications Go Here", "Trade Page Goes Here", "People Online Page Goes Here"};
for(int i=0;i<5;i++){
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[i]));
tabName.add((strings[i]));
}
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
getChildFragmentManager().beginTransaction().addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Note that we are passing childFragmentManager, not FragmentManager
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onResume() {
super.onResume();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
To be able to do this from another Fragment you will need to send a something in a Bundle, such as the position of the page, then do something like this:
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(YOUR_PAGE, youPage);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack("Name").commit();
Then in your HomeFragment:
Bundle bundle = this.getArguments();
if (bundle != null) { viewPager.setCurrentItem(bundle.getInt(YOUR_PAGE) }
I am creating project for "Drawer with Swipe Tab". There i used a webview in fragment and i want to load Webview URL from Another AppCompatActivity. How can i do it?
Fragment Class:
public class SocialFragment extends Fragment {
ProgressBar pb_per;
public WebView mWebView;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.social_layout, container, false);
pb_per = (ProgressBar) view.findViewById(R.id.progressBar_book1);
mWebView = (WebView) view.findViewById(R.id.web_book1); //This is the id you gave for webview
//--------------------------- to over ride keyboard error ------(1)
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
//--------------------------------------------------
mWebView.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
mWebView.setBackgroundColor(Color.parseColor("#FFFFFF"));
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(false);
// Load URL
mWebView.loadUrl("http://www.twitter.com");
mWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return view;
}
//===================================================================
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
pb_per.setVisibility(View.VISIBLE);
// multi_per.setVisibility(ProgressBar.GONE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pb_per.setVisibility(View.GONE);
// multi_per.setVisibility(ProgressBar.VISIBLE);
}
}
}
TabFragment.Java Class
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to Position .
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SocialFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
// This method returns the title of the tab according to the position.
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Facebook";
case 1 :
return "Twitter";
}
return null;
}
}
}
AppCompatActivity class:
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup the DrawerLayout and NavigationView
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
// Lets inflate the very first fragment
// Here , we are inflating the TabFragment as the first Fragment
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
// Setup click events on the Navigation View Items.
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
//###############################From Here I Call WEBVIEW URL #######################
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
}
return false;
}
});
// Setup Drawer Toggle of the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
I had Tried #cprakashagr Given Solutation but getting error See below Image
See Error ScreenShot
Use localBroadCastManager
WebViewHavingActivity
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mWebViewLoader);
super.onPause();
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mWebViewLoader) to receive Intents
// with actions named "WebView".
LocalBroadcastManager.getInstance(this).registerReceiver(
mWebViewLoader, new IntentFilter("WebView"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "WebView" is broadcasted.
private BroadcastReceiver mWebViewLoader = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mWebView.post(new Runnable() {
#Override
public void run() {
mWebView.loadUrl("http://google.com");
}
});
}
};
CallingActivity
LocalBroadcastManager.getInstance(JobDetailScreen.this).sendBroadcast(new Intent("WebView"));
This Work for me Thanks For trying me to Help
SocialFragment.mWebView.post(new Runnable() {
public void run() {
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
});
Hi I want to change view with the drawer selection, it work but the first view stay under the new one...
I have a superimposition of layout...
What Should i do?
Also How can i recover the id of current layout?
public class display extends MainActivity {
private String[] drawerListViewItems;
private ListView drawerListView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_launcher,
R.string.open,
R.string.close
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle SaveInstanceState) {
super.onPostCreate(SaveInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem target) {
if (actionBarDrawerToggle.onOptionsItemSelected(target)) {
return true;
}
return super.onOptionsItemSelected(target);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View v, int pos, long id) {
Toast.makeText(display.this, ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
selectItem(pos);
drawerLayout.closeDrawer(drawerListView);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
break;
case 1:
fragment = new test2();
break;
case 2:
fragment = new test3();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.drawer_layout, fragment).commit();
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
drawerLayout.closeDrawer(drawerListView);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
}
If the first view remains under the new one, maybe the xml file associated with the new fragment doesn't have a background defined and it might be transparent.
Try to define android:background in the root element of the new view.
For the fragment id question, I think it's not possible to recover the id. You could store it in a global variable, or you can use string tags in order to identify the fragments, like it's done here:
get the latest fragment in backstack