I am building an OpenGL live wallpaper. I decided to have a Navigation Drawer in my main activity since there are a lot of features the user will have access to.
The problem/issue
If I press the "hardware" back button to normally close an app the initial fragment that is shown just refreshes and the app never closes. If I hit the home button and go back to the app everything is a black screen. I've searched all throughout Google thinking that maybe I wasn't destroying the MainActivity properly or for a way to terminate a fragment. I've tried calling finish() in the main activity's onDestroy method. I've tried utilizing the remove method from fragment manager in each fragments onDetach method per posts that I've found online. Nothing has worked. I'm stumped. I've set debug points in the main activity on the onDestroy method and on the fragments onDetach method with no error being produced or any information being given. At this point I am clueless. Here's my MainActivity class.
public class MainActivity extends AppCompatActivity implements OnNavigationItemSelectedListener, OnPostSelectedListener{
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
TextView usrTag, tagrEmail;
CircleImageView tagrPic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).addToBackStack("PreviewFragment").commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
usrTag = (TextView)header.findViewById(R.id.usrName);
tagrEmail = (TextView)header.findViewById(R.id.usrEmail);
tagrPic = (CircleImageView)header.findViewById(R.id.usrImg);
Log.i("MainActivity: ", "User Photo: " + getProfilePic(this));
usrTag.setText(getUserName(getBaseContext()));
tagrEmail.setText(getUserEmail(getBaseContext()));
GlideUtils.loadProfileIcon(getProfilePic(getBaseContext()), tagrPic);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment = null;
Class fragmentClass = null;
int id = item.getItemId();
if (id == R.id.nav_home) {
fragmentClass = PreviewFragment.class;
} else if (id == R.id.nav_custom) {
startCustomLabelCreator();
} else if (id == R.id.nav_mylabels) {
} else if (id == R.id.nav_commLabels) {
fragmentClass = PostsFragment.class;
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void startCustomLabelCreator(){
Intent cLC = new Intent(getBaseContext(), CreateLabel.class);
startActivity(cLC);
}
#Override
public void onPostComment(String postKey) {
}
#Override
public void onPostLike(String postKey) {
}
#Override
public void onPhotoSelected(String photoUrl) {
}
#Override
protected void onDestroy() {
super.onDestroy();
finish();
}
}
My Fragments
public class PostsFragment extends Fragment implements ConfirmSelectedPhotoListener{
public static final String TAG = "PostsFragment";
private static final String KEY_LAYOUT_POSITION = "layoutPosition";
private int mRecyclerViewPosition = 0;
private OnPostSelectedListener mListener;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter<PostViewHolder> mAdapter;
public PostsFragment() {
// Required empty public constructor
}
public static PostsFragment newInstance() {
PostsFragment fragment = new PostsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_posts, container, false);
rootView.setTag(TAG);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
Log.d(TAG, "Restoring recycler view position (all): " + mRecyclerViewPosition);
Query allPostsQuery = FirebaseUtil.getPostsRef();
mAdapter = getFirebaseRecyclerAdapter(allPostsQuery);
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
// TODO: Refresh feed view.
}
});
mRecyclerView.setAdapter(mAdapter);
}
private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class, R.layout.post_item, PostViewHolder.class, query) {
#Override
public void populateViewHolder(final PostViewHolder postViewHolder,
final Post post, final int position) {
setupPost(postViewHolder, post, position, null);
}
#Override
public void onViewRecycled(PostViewHolder holder) {
super.onViewRecycled(holder);
// FirebaseUtil.getLikesRef().child(holder.mPostKey).removeEventListener(holder.mLikeListener);
}
};
}
private void setupPost(final PostViewHolder postViewHolder, final Post post, final int position, final String inPostKey) {
postViewHolder.setPhoto(post.getThumb_url());
Log.d(TAG, post.getThumb_url());
postViewHolder.setText(post.getText());
postViewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
(long) post.getTimestamp()).toString());
final String postKey;
if (mAdapter instanceof FirebaseRecyclerAdapter) {
postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
} else {
postKey = inPostKey;
}
Author author = post.getAuthor();
postViewHolder.setAuthor(author.getFull_name(), author.getUid());
postViewHolder.setIcon(author.getProfile_picture(), author.getUid());
ValueEventListener likeListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postViewHolder.setNumLikes(dataSnapshot.getChildrenCount());
if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, getActivity());
} else {
postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, getActivity());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseUtil.getLikesRef().child(postKey).addValueEventListener(likeListener);
postViewHolder.mLikeListener = likeListener;
postViewHolder.setPostClickListener(new PostViewHolder.PostClickListener() {
#Override
public void showComments() {
Log.d(TAG, "Comment position: " + position);
mListener.onPostComment(postKey);
}
#Override
public void toggleLike() {
Log.d(TAG, "Like position: " + position);
mListener.onPostLike(postKey);
}
#Override
public void savePhotoUrl() {
//mListener.onPhotoSelected(post.getFull_url());
showLabelConfirm(post.getFull_url());
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null && mAdapter instanceof FirebaseRecyclerAdapter) {
((FirebaseRecyclerAdapter) mAdapter).cleanup();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save currently selected layout manager.
int recyclerViewScrollPosition = getRecyclerViewScrollPosition();
Log.d(TAG, "Recycler view scroll position: " + recyclerViewScrollPosition);
savedInstanceState.putSerializable(KEY_LAYOUT_POSITION, recyclerViewScrollPosition);
super.onSaveInstanceState(savedInstanceState);
}
private int getRecyclerViewScrollPosition() {
int scrollPosition = 0;
// TODO: Is null check necessary?
if (mRecyclerView != null && mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
return scrollPosition;
}
#Override
public void onSelectedPhoto(String selectPhoto) {
mListener.onPhotoSelected(selectPhoto);
}
public interface OnPostSelectedListener {
void onPostComment(String postKey);
void onPostLike(String postKey);
void onPhotoSelected(String photoUrl);
}
private void showLabelConfirm(String uriBmp) {
FragmentManager fm = getFragmentManager();
PhotoDialogFragment editNameDialogFragment = PhotoDialogFragment.newInstance(uriBmp);
// SETS the target fragment for use later when sending results
editNameDialogFragment.setTargetFragment(PostsFragment.this, 300);
editNameDialogFragment.show(fm, "fragment_edit_name");
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnPostSelectedListener) {
mListener = (OnPostSelectedListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnPostSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
Second Fragment:
public class PreviewFragment extends RajBaseFragment {
#Override
public ISurfaceRenderer createRenderer() {
return new PreviewRenderer(getContext());
}
}
Which extends:
public abstract class RajBaseFragment extends Fragment implements IDisplay, View.OnClickListener {
protected FrameLayout mLayout;
protected ISurface mRajawaliSurface;
protected ISurfaceRenderer mRenderer;
public RajBaseFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// Inflate the view
mLayout = (FrameLayout) inflater.inflate(getLayoutID(), container, false);
mLayout.findViewById(R.id.relative_layout_loader_container).bringToFront();
// Find the TextureView
mRajawaliSurface = (ISurface) mLayout.findViewById(R.id.rajwali_surface);
// Create the loader
mRenderer = createRenderer();
onBeforeApplyRenderer();
applyRenderer();
return mLayout;
}
protected void onBeforeApplyRenderer() {
}
protected void applyRenderer() {
mRajawaliSurface.setSurfaceRenderer(mRenderer);
}
#Override
public void onClick(View v) {
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mLayout != null)
mLayout.removeView((View) mRajawaliSurface);
}
#Override
public int getLayoutID() {
return R.layout.rajawali_textureview_fragment;
}
}
I've tried all the recommendations below so far and the primary fragment that is set in the MainActivity's onCreate method still gets refreshed/reloaded when the back button is pressed rather than the app exiting/closing.
In your onNavigationItemSelected method, you are replacing the current fragment with fragment even in cases where fragment is null, which has undefined effects. You should not do that.
One fix is to replace this code block:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
with this one:
if (fragmentClass != null) {
fragment = fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).addToBackStack().commit();
}
(and then leave out the fragment transaction below this point).
Also, there is a call to finish in the onDestroy method, which probably is not causing the problem but should be taken out because it does not make any sense there.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
replace your onOptionsItemSelected() with mine.
Don't include your first fragment into backstack.
Try to change you fragment transaction line code without addToBackStack
as below:
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
While adding fragment with addToBackStack, this allows back
navigation for added fragment.Because of fragment in backstack,
empty(black) activity layout will be displayed.
Change onBackPressed() as below which automatically close app after if no any Fragment found in FragmentManager:
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getSupportFragmentManager().popBackStack();
}
}
Also you can see some similar Q/A on below links which helps you get more idea to solve your problem:
Fragment pressing back button
In Fragment on back button pressed Activity is blank
Transaction of fragments in android results in blank screen
It's solved my blank screen problem. Hope its helps you.
Try this code, hope this helps you, take necessary stuffs which are required for you. Also, try running this project in Android studio, it works.
https://github.com/asifali22/Navigation_Health/blob/master/app/src/main/java/com/thenewboston/mynavigation/MainActivity.java
When user press to back button it'll check fragment manager's backstack and if backstack entity count is bigger than 0 (this means there's a fragment in backstack) it'll popBackStack else it'll finish activity.
If you add your initial fragment to backstack, when user press back button they'll see a blank screen.
Also when you init your activity if you need to put a fragment it's a best practice to check if saved instance state is null. Here i modified some part of your code.
if(savedInstanceState == null){
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
}
I hope this'll help you. If you still have problem let me know.
Good luck.
create subclass for ISurface and override onKeyDown method like this
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.e("Custom View", "onKeyDown");
//return super.onKeyDown(keyCode, event);
return false;
}
Could be related with the lifecycle...
Try using GLSurfaceView. I believe is easier for what you want, is special for OpenGL rendering and there is plenty information about it. Examples, lifecycle among others. Let me know if helped. If not, please, provide more info.
Related
I've read countless topics regarding saving and retrieving the state of Fragments by now. Unfortunately nothing has worked for me and Bundle savedInstanceState is always returning null. What i wanna do is implement a "shopping cart" which remembers the items the user selected. To make that possible I just want to save one variable of the Fragment and retrieve it once the Fragment is called again.
Not only do I want to make the fragment retain it's state when called from the backstack, but also when opening it from the BottomNavigationView. Or does it even make any difference?
Here is the parent Activity class of all the Fragments:
public class ShopMainViewScreen extends AppCompatActivity implements ShopFragment.OnFragmentInteractionListener, SearchFragment.OnFragmentInteractionListener, ... {
Fragment mContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
loadFragment(new ShopFragment());
mContent = getSupportFragmentManager().findFragmentById(R.id.fragmentplace);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new ShopFragment();
loadFragment(fragment);
return true;
case R.id.navigation_search:
fragment = new SearchFragment();
loadFragment(fragment);
return true;
case R.id.navigation_shoppingCart:
fragment = new CartFragment();
loadFragment(fragment);
return true;
case R.id.navigation_settings:
fragment = new SettingsFragment();
loadFragment(fragment);
return true;
}
return false;
}
};
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentplace, fragment)
.addToBackStack(null)
.commit();
}
return false;
}
This is the Fragment containing the variable (mShoppingCart which ought to be stored and retrieved).
public class CartFragment extends Fragment {
private String mTitle;
private int mQuantity;
ArrayList < String > mShoppingCart;
private OnFragmentInteractionListener mListener;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Log.i("onSaveInstanceState", "entered");
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putStringArrayList("CART", mShoppingCart);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
Log.i("onActivityCreated", "entered");
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
Log.i("SavedInstanceState", " not null");
mShoppingCart = savedInstanceState.getStringArrayList("CART");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("onCreate", "entered");
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString("PRODUCTTITLE");
mQuantity = getArguments().getInt("QUANTITY");
}
if (savedInstanceState == null) {
Log.i("InstanceState", "is null");
mShoppingCart = new ArrayList < > ();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
validateCart(mTitle, mQuantity);
return inflater.inflate(R.layout.shoppingcart_fragment_layout, container, false);
}
#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;
}
Any help is appreciated.
savedInstanceState is only hydrated during configuration changes or when the app is backgrounded & brought back to the foreground. To save the state of a shopping cart throughout a user's session consider using a view model attached to the parent activity. You could also try persisting the cart in SQLite if you'd like that data to be retained across multiple sessions.
I have implement an app that has a fragment system exactly like Instagram.
When I select a tab in bottom tab the fragment is replaced in the container.
My problem is when I go to another fragment and get back to this fragment the data is reloading and the fragment recreating.
I have searched and no answer helped me. I see this answer and I think it's correct, but I don't know how to use it and what FragmentMetaData is.
This is my main activity:
public class MainActivity extends FragmentActivity {
//set this tablayout to puplic static, so we can access this from othere fragment
public static TabLayout tabLayout_bottom;
Fragment fragmentHome = new FragmentHome();
Fragment fragmentSearch = new FragmentSearch();
Fragment fragmentLikes = new FragmentLikes();
Fragment fragmentProfile = new FragmentProfile();
//use fragment manager to manage fragment
private FragmentManager fragmentManager = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set current fragment to FragmentHome when activity start
this.getSupportFragmentManager().beginTransaction().replace(R.id.container, fragmentHome).commit();
tabLayout_bottom = (TabLayout) findViewById(R.id.tabs_bottom_home);
//this code change color of statusbar if current android version is more then lollipop
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
createTabIcons_bottom();
//this method change the language of hole app. so if user change his device language, the app not changing
//if you want persian change "en" to "fa"
String languageToLoad = "en"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
}
private void createTabIcons_bottom() {
//this set icon for each tab
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_home_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_search_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_add_box_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_favorite_black_24dp));
tabLayout_bottom.addTab(tabLayout_bottom.newTab().setIcon(R.drawable.ic_person_black_24dp));
//set color for each icon
tabLayout_bottom.getTabAt(0).getIcon().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(1).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(2).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(3).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.getTabAt(4).getIcon().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), PorterDuff.Mode.SRC_IN);
tabLayout_bottom.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//set color when tab selected
int tabIconColor = ContextCompat.getColor(getApplicationContext(), R.color.colorAccent);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
if (tab.getPosition() == 0) {
GotoFragmentHome();
}
else if (tab.getPosition() == 1) {
GotoFragmentSearch();
}
else if (tab.getPosition() == 2) {
GotoActivityAdd();
}
else if (tab.getPosition() == 3) {
GotoFragmetnLikes();
}
else if (tab.getPosition() == 4) {
GotoFragmetnProfile();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//set color if tab unselect
int tabIconColor = ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
//each method is for a fragment that use when a tab seleted
//the addToBackStack method hold that fragment in a stack so when back pressed, geting back to last fragment
public void GotoFragmentHome() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentHome).addToBackStack("home").commit();
}
public void GotoFragmentSearch() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentSearch).addToBackStack("search").commit();
}
public void GotoActivityAdd() {
startActivity(new Intent(getApplicationContext(), ActivityAdd.class));
}
public void GotoFragmetnLikes() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentLikes).addToBackStack("likes").commit();
}
public void GotoFragmetnProfile() {
fragmentManager.beginTransaction().replace(R.id.container, fragmentProfile).addToBackStack("profile").commit();
}
#Override
public void onBackPressed() {
//this says that if no fragment was in stack, so exit app
if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
else {
//exit hole app
moveTaskToBack(true);
return;
}
}
}
And this is one of my fragments:
public class FragmentSearch extends Fragment {
private LinearLayout toolbar_search;
public FragmentSearch() {
// Required empty public constructor
}
View rootView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_search, container, false);
//select search tab if user back to this fragment
MainActivity.tabLayout_bottom.getTabAt(1).select();
//save current tab position in sharedpreferance. so if uer get back from Add Activity, select last tab
int tabselected=MainActivity.tabLayout_bottom.getSelectedTabPosition();
SharedPreferences.Editor editor=getActivity().getSharedPreferences("selectedtab", Context.MODE_PRIVATE).edit();
editor.putInt("selectedtab",tabselected);
editor.commit();
toolbar_search=(LinearLayout) rootView.findViewById(R.id.toolbar_in_searchfragment);
toolbar_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), ActivitySearch.class));
}
});
return rootView;
}
}
If somebody help me I'd be grateful. I see the savedInstanceState in some answers but that has not worked for me.
In my android application I have a ViewPager and 5 fragments. I previously used viewPager.setCurrentItem() to navigate, but the requirement for navigation animation has changed; For an example in some fragments when a previous fragment is called, we were asked not to show going back (left to right animation), instead show the user their moving to the next fragment (right to left animation). For an example in some cases user has to insert the same data again and again so instead of creating new fragmnets for these, we re-used the existing ones we created- so when the viewPager.setCurrentItem() is calling a fragment in the back (ex: we are now in 20th fragment and we are calling 10th fragment) it goes back and shows left to right animation.
Now we are not using the viewPager.setCurrentItem() method to navigate, instead we use FragmentTransaction. However we did not remove the fragments from the ViewPager anyway, expecting to complete this with minimum work (we are at the end of project when this requirement appeared)
But when we use the FragmentTransaction we have a new issue now. When we come back the onCreateView of fragmnets are getting called all the time! This didn't happen when we were using viewPager.setCurrentItem(). Lot of our code which should run only once are in this onCreateView.
Another issue is setUserVisibleHint() is called only in first fragment and that is also only at the initial run! All of our code which should run every time the fragmnet is displayed is located in this method.
Below is an example code, which demonstrate our issue.
MainActivity.java
public class MainActivity extends FragmentActivity {
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager=(ViewPager)findViewById(R.id.viewPager);
viewPager.setAdapter(new MyPagerAdapter2(getSupportFragmentManager()));
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (viewPager.getCurrentItem() == 0) {
return true;
}
if (viewPager.getCurrentItem() == 1) {
return true;
}
if (viewPager.getCurrentItem() == 2) {
return true;
}
if (viewPager.getCurrentItem() == 3) {
return true;
}
if (viewPager.getCurrentItem() == 4) {
return true;
}
return false;
}
});
}
private class MyPagerAdapter2 extends FragmentPagerAdapter {
public MyPagerAdapter2(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FirstFragment1.newInstance("FirstFragment_1");
case 1: return SecondFragment1.newInstance("SecondFragment_1");
case 2: return ThirdFragment1.newInstance("ThirdFragment_1");
case 3: return FourthFragment1.newInstance("FourthFragment_1");
case 4: return FifthFragment1.newInstance("FifthFragment_1");
default: return FirstFragment1.newInstance("DefaultFragment_1");
}
}
#Override
public int getCount() {
return 1;
}
}
public void setCurrentItem(int which) {
if(viewPager != null && which >= 0 && which <= 4) {
viewPager.setCurrentItem(which);
}
}
}
FirstFragment1.java
public class FirstFragment1 extends Fragment {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag_1, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
tv.setText("FRAGMENT 01");
textView=(TextView)v.findViewById(R.id.textView1);
textView.setText("Fragment Name : - 01");
Log.d("FRAGMENT_01", "ON_CREATE");
Button button1 = (Button) v.findViewById(R.id.nextButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity() != null) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.firstFragment, new SecondFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return v;
}
public static FirstFragment1 newInstance(String text) {
FirstFragment1 f = new FirstFragment1();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
Activity a = getActivity();
if (a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
// textView.setText("Fragment Name : - 01");
Log.d("FRAGMENT_01", "VISIBLE_HINT");
}
}
}
SecondFragment1.java
public class SecondFragment1 extends Fragment {
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag_1, container, false);
TextView tv = (TextView) v.findViewById(R.id.tvFragSecond);
tv.setText("FRAGMENT 03");
textView=(TextView)v.findViewById(R.id.textView2);
textView.setText("Fragment Name : - 02");
Log.d("FRAGMENT_02", "ON_CREATE");
Button button=(Button)v.findViewById(R.id.printButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getActivity() != null) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.secondFrag, new FirstFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
Button button1=(Button)v.findViewById(R.id.nextButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity() != null) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.secondFrag, new ThirdFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return v;
}
public static SecondFragment1 newInstance(String text) {
SecondFragment1 f = new SecondFragment1();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
Log.d("FRAGMENT_02","VISIBLE_HINT");
}
}
}
As you can see in our code, we use below to navigate between Fragments. (Below code shows navigating from first fragmnet to second)
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.from_right, R.anim.to_left);
transaction.replace(R.id.firstFragment, new SecondFragment1());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack(null);
transaction.commit();
Looking at our code, and considering we have added the ViewPager as well, how can we make sure that onCreateView is only called once and setUserVisibleHint is called everytime the fragment is displayed?
there is challenges when using setUserVisibleHint is called.try viewPager.setOffscreenPageLimit(5); and use setMenuVisibility method and if you launch app on any fragment by notification
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if(menuVisible && isResumed()){
// do your work here
}
if(!isResumed()){
// do your work when Activity is created
}
}
Put all of your code which you want should not be called everytime in onCreate() method and the code which you want should be called everytime in onCreateView() method.
Hello everyone I'm developing an app that uses old navigation drawer approach. When I update 'com.android.support:appcompat-v7:23.1.1' to 'com.android.support:appcompat-v7:23.4.0' my navigation drawer not opening.
I debugged code and look for deprecated items but could not find any error code or message. Everything works perfectly but navigation drawer is not opening. Here is my code. Thanks in advance.
MainActivity.class
public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, TapuInterface.IAuthorization {
TapuUtils tapuUtils = new TapuUtils();
String userMail, userPassword;
SharedPreferences.Editor editor;
SharedPreferences preferences;
Tracker mTracker;
Bundle bundle;
String tapuAuth = "false";
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleAnalytics.getInstance(this).setLocalDispatchPeriod(15);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
Countly.sharedInstance().init(this, getString(R.string.countly_server), getString(R.string.countly_key));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,(DrawerLayout) findViewById(R.id.drawer_layout));
ActionBar mActionBar = getSupportActionBar();
assert mActionBar != null;
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF297AA6));
if (savedInstanceState == null) {
bundle = getIntent().getExtras();
userMail = bundle.getString("personname");
userPassword = bundle.getString("personpassword");
tapuAuth = bundle.getString("tapu");
}
TapuCredentials.setUserMail(userMail);
TapuCredentials.setUserPassword(userPassword);
TapuCredentials.setTapuAuth(tapuAuth);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, MainMapFragment.newInstance(position + 1), "MapFragment")
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit_alert))
.setCancelable(true)
.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
LoginActivity.fa.finish();
}
})
.setNegativeButton(getString(R.string.no), null)
.show();
}
#Override
public void onStart() {
super.onStart();
Countly.sharedInstance().onStart();
}
#Override
public void onStop() {
super.onStop();
Countly.sharedInstance().onStop();
}
#Override
protected void onResume() {
super.onResume();
mTracker.setScreenName(getResources().getString(R.string.main_screen));
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
Here is my NavigationDrawer.class
public class NavigationDrawerFragment extends Fragment {
private static NavigationDrawerAdapter myAdapter;
public static ArrayList<ListItem> myItems = new ArrayList<>();
public static UserCredentials mUserCredentials = new UserCredentials();
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private DynamicListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
static LegendFragment frLegend = new LegendFragment();
Button mEditLayers, mShowLegend;
String personName,userType,tapucontrol;
TextView mLayersText;
static FragmentManager fragmentManager;
Bundle extras;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
if (savedInstanceState == null) {
extras = getActivity().getIntent().getExtras();
if(mUserCredentials.getUserName()==null || mUserCredentials.getPassword()==null){
mUserCredentials.setUserAccount(extras.getString("username"), extras.getString("password"));
}
personName = extras.getString("personname");
userType = extras.getString("usertype");
tapucontrol = extras.getString("tapu");
}
mDrawerListView = (DynamicListView) rootView.findViewById(R.id.dynamiclistivew);
mLayersText = (TextView) rootView.findViewById(R.id.textview_layers);
myAdapter = new NavigationDrawerAdapter(getActivity(), myItems);
mDrawerListView.setAdapter(myAdapter);
fragmentManager = getFragmentManager();
mDrawerListView.setCheeseList(myItems);
mDrawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mEditLayers = (Button) rootView.findViewById(R.id.button);
mShowLegend = (Button) rootView.findViewById(R.id.legendbutton);
mEditLayers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEditLayers.getText().equals("Düzenle")) {
myAdapter.setEditMode(true);
mEditLayers.setText(getActivity().getString(R.string.ok));
} else {
myAdapter.setEditMode(false);
mEditLayers.setText(getActivity().getString(R.string.editlayers));
}
}
});
return rootView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
null, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
FragmentTransaction ft = fragmentManager.beginTransaction();
if (frLegend.isAdded()) {
ft.remove(frLegend);
ft.commitAllowingStateLoss();
mEditLayers.setVisibility(View.VISIBLE);
mLayersText.setText("Katmanlar");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
// showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
Intent s = new Intent(getActivity(), SearchMainActivity.class);
s.putExtra("username", mUserCredentials.getUserName());
s.putExtra("password", mUserCredentials.getPassword());
s.putExtra("tapu",tapucontrol);
startActivity(s);
break;
case R.id.action_basemaps:
Intent cb = new Intent(getActivity(), BaseMapsActivity.class);
startActivity(cb);
break;
case R.id.action_addlayer:
if (isNetworkAvailable(getActivity())) {
Intent al = new Intent(getActivity(), AddLayerActivity.class);
al.putExtra("usertype", userType);
startActivity(al);
} else {
Toast.makeText(getActivity(), "Lütfen internet bağlantınızı kontrol ediniz.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_about:
Intent au = new Intent(getActivity(), AboutActivity.class);
au.putExtras(extras);
startActivity(au);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class ListItem {
String textdata;
Integer progress;
public ListItem(String textdata, int progress) {
this.textdata = textdata;
this.progress = progress;
}
public boolean equals(Object o) {
ListItem ndListItemObject = (ListItem) o;
return this.textdata.equalsIgnoreCase(ndListItemObject.textdata);
}
}
public void addLayersection(String name, int progress) {
ListItem listItem = new ListItem(name, progress);
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.contains(listItem)) {
myItems.remove(listItem);
} else {
myItems.add(0, listItem);
}
}
}
myAdapter.notifyDataSetChanged();
}
public int getListSizee() {
return myItems.size();
}
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
The Drawer is locked.
Change
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
to
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
Here is the late solution that I find with myself. drawerOpenCloseControl is boolean flag. I am controlling true or false. And then open and close manually.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(drawerOpenCloseControl){
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
drawerOpenCloseControl = false;
}
else{
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerOpenCloseControl = true;
}
break;
}
return super.onOptionsItemSelected(item);
}
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");
}
});