Display Settings Window from MapFragment - java

from within a MapFragment I'd like to display some kind of settings window. What would be the best way to do that?
Replace the fragment? Create some kind of overlaying view? AlertDialog?
How would I best implement it?
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//...
}
});
Thanks

Put the settings in a diaglog fragment activated from button in the actionbar have an interface so you can update the map in background.
See this live in my app
Button in action bar.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_settings"
android:icon="#drawable/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
android:showAsAction="always"
yourapp:showAsAction="always"/>
Process the button click
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int x = item.getItemId();
switch (x) {
case R.id.action_settings:
showSettingsDialog();
return true;
do something useful show the fragment.
private void showSettingsDialog() {
FragmentManager fm = getSupportFragmentManager();
MapSettings editSettingsDialog = new MapSettings();
editSettingsDialog.show(fm, "fragment_edit_name");
}
The complete mapsettings class.
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public static final String MAP_TYPE = "com.gosylvester.bestrides.settings.maptype";
BestRidesSettingsDialogListener activity;
SharedPreferences sharedpref;
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
getDialog().setTitle(R.string.app_name);
View view = inflater.inflate(R.layout.activity_map_settings, container);
RadioGroup rg = (RadioGroup) view.findViewById(R.id.radioGroup1);
// initialize to the shared preferences value
rg.clearCheck();
... homemade glue to get the initial setting.
GoPreferences.getInt(getActivity(),MAP_TYPE,GoogleMap.MAP_TYPE_NORMAL);
RadioButton rb = null;
switch (x) {
case GoogleMap.MAP_TYPE_HYBRID:
rb = (RadioButton) view.findViewById(R.id.RDOHybrid);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_NORMAL:
rb = (RadioButton) view.findViewById(R.id.RDORoad);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
rb = (RadioButton) view.findViewById(R.id.RDOSatelite);
rb.setChecked(true);
break;
case GoogleMap.MAP_TYPE_TERRAIN:
rb = (RadioButton) view.findViewById(R.id.RDOTerrain);
rb.setChecked(true);
break;
}
// set the listener after setting up
rg.setOnCheckedChangeListener(this);
return view;
}
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
// save the settings
}
impliment the interface on your map activity so the map can be changed from the dialog fragment.
public class KmlReader extends ActionBarActivity implements
BestRidesSettingsDialogListener, SnapshotReadyCallback,
OnMapLoadedCallback {
#Override
public void onMapSettingsChange(int mapType) {
// TODO Auto-generated method stub
if (mMap != null) {
mMap.setMapType(mapType);
}
}
Good Luck
Danny117

Related

How to refresh a Textview in a fragment which receives data from a Listview in an activity which doesn't host that fragment

I have created a bottomNavigation bar which consists of 5 Fragments, so once each tab is clicked it will switch from one fragment to another.
The question is:The second fragment (Search fragment) have 1 TextView with setOnClickListener so once it is been licked a layout activity will open on the top which includes a ListView to allow the user to select/click on a specific Item, so later on this selected item info should be displayed on that TextView within the(Search fragment).
The issue is that this Textview won't be updated, unless I call the mainActivity to so all fragments in bottom Navigation bar will be updated
My question is how I can refresh that specific fragment without calling the MainActivity.
public class MainActivity extends AppCompatActivity {
final Fragment f1 = new HomeFragment();
final Fragment f2 = new SearchFragment();
final Fragment f3 = new CameraFragment();
final Fragment f4 = new ChatFragment();
final Fragment f6 = new LogginFragment();
final FragmentManager fm = getSupportFragmentManager();
Fragment active = f1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationViewEx bnve = (BottomNavigationViewEx) findViewById(R.id.bottom_navigation);
bnve.enableAnimation(false);
bnve.enableShiftingMode(false);
bnve.enableItemShiftingMode(false);
bnve.setOnNavigationItemSelectedListener(navListener);
if(SharePrefManager.getInstance(this).isLoggedin()){
finish();
startActivity(new Intent(this, SuccessActivity.class));
return;
}
fm.beginTransaction().add(R.id.fragment_container, f6, "6").hide(f6).commit();
//fm.beginTransaction().add(R.id.fragment_container, f5, "5").hide(f5).commit();
fm.beginTransaction().add(R.id.fragment_container, f4, "4").hide(f4).commit();
fm.beginTransaction().add(R.id.fragment_container, f3, "3").hide(f3).commit();
fm.beginTransaction().add(R.id.fragment_container, f2, "2").hide(f2).commit();
fm.beginTransaction().add(R.id.fragment_container, f1, "1").commit();
}
public BottomNavigationViewEx.OnNavigationItemSelectedListener navListener =
new BottomNavigationViewEx.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fm.beginTransaction().hide(active).show(f1).commit();
active = f1;
return true;
case R.id.nav_search:
fm.beginTransaction().hide(active).show(f2).commit();
active = f2;
return true;
case R.id.nav_camera:
fm.beginTransaction().hide(active).show(f3).commit();
active = f3;
return true;
case R.id.nav_chat:
fm.beginTransaction().hide(active).show(f4).commit();
active = f4;
return true;
case R.id.nav_account:
fm.beginTransaction().hide(active).show(f6).commit();
active = f6;
return true;
}
return false;
}
};
}
------------------------SearchFragment Class----------------------------------
This is the search fragment which has the textView (Categories) which supposed to be updated/be refershed without calling the MainActivity
public class SearchFragment extends Fragment {
private Context mContext;
TextView Categories;
static boolean status = false;
String SelectedItem;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search,container,false);
Categories = (TextView) v.findViewById(R.id.categories);
SelectedItem = DataHolder.getInstance().getItem();
Categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mContext, AllCateActivity.class));
}
});
if(status){Categories.setText(SelectedItem);}
return v;
}
public void ChangeStatus(Boolean status){
this.status = status;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
}
--------------------------DataHolder Class---------------------------------
This works as a design pattern to share arguments between the search fragment and Categories_Activity
public class DataHolder {
private static DataHolder dataHolder = null;
private DataHolder() {
}
public static DataHolder getInstance() {
if (dataHolder == null)
{
dataHolder = new DataHolder();
}
return dataHolder;
}
private String item;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
--------------------------Categories_Activity---------------------------------
This Activity once it's being called a listview will show allowing user to select an item. So once an Item has been selected it will start the MainActivity in order to refresh the Text field in the search Fragment
public class Categories_Activity extends AppCompatActivity implements View.OnClickListener {
ImageView BacktoMainCate;
ListView subCate;
public String selectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_subcategory);
subCate = (ListView)findViewById(R.id.listview_subcate);
BacktoMainCate = (ImageView)findViewById(R.id.BacktoMainCate);
BacktoMainCate.setOnClickListener(this);
final SearchFragment SF = new SearchFragment();
subCate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItem = String.valueOf(parent.getItemAtPosition(position));
DataHolder.getInstance().setItem(selectedItem);
SF.ChangeStatus(true);
Intent in = new Intent(Categories_Activity.this,SuccessActivity.class);
startActivity(in);
});
}
#Override
public void onClick(View v) {
if (v == BacktoMainCate){
//startActivity(new Intent(this,AllCateActivity.class));
finish();
}
}
}
I have used SharedPreferences on both Fragment/Activity life cycle.
So once the Categories_Activity get started, Main Activity will go in onPause and with it all its Fragments will be put in onPause. When user clicks on one of the ListView items in the Categories_Activity, data of that selected item will be store inside SharedPreferences like:
PreferenceManager.getDefaultSharedPreferences(Categories_Activity .this)
.edit().putString(key, selectedItemInfo).apply();
Then override onResume() method inside MainActivity and SearchFragment:
#Override
public void onResume() {
super.onResume();
String value = PreferenceManager.getDefaultSharedPreferences(getContext())
.getString(key, "");
if (value != null && !value.isEmpty()) {
Categories.setText(value);
PreferenceManager.getDefaultSharedPreferences(getContext()).edit().remove(key);
}
}

android using getchildFragmentManager to retain fragments when replase and reding

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.

Android - NullPointerException in Fragment after callback

This is the first time I work with Fragments and I don't understand very well how to manage them. In this case I have two fragments that I show dinamically in a FrameLayout with id fragment_place. The issue is probably with the fragmentTransaction(addtobackstack / popbackstack).
In Fragment2 I show a popupmenu when I press the menubutton on the mobile and it works as expected the first time, but after I go back to the previous fragment and return to fragment2 now If I press the menubutton I get the following error
java.lang.NullPointerException
at android.support.v7.view.menu.MenuBuilder.<init>(MenuBuilder.java:216)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:103)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:78)
at android.support.v7.widget.PopupMenu.<init>(PopupMenu.java:63)
at package.Fragment2.showPopup(Fragment2.java:93)
Below is the code for the mainactivity and fragment2, this is driving me crazy, any help will be much appreciated.
public class MainActivity extends AppCompatActivity implements Fragment1.onEvent {
Fragment1 frag;
Fragment2 frag2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag = new Frag1();
// Begin the transaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place, frag);
ft.commit();
}
#Override
public void onEventSelected(String key) {
frag2 = new Frag2();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_place,frag2);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onBackPressed(){
FragmentManager ft = getSupportFragmentManager();
if (ft.getBackStackEntryCount() > 0) {
ft.popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_MENU:
if (action == KeyEvent.ACTION_UP) {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_place);
if (f instanceof Fragment2) {
sendBroadcast();
}
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
private void sendBroadcast(){
Intent intent = new Intent("popup_menu");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}}
This is the problematic fragment. The error lines are basically the method showPopup
public class Fragment2 extends Fragment {
private String key;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, parent, false);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
new IntentFilter("popup_menu"));
return view;
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
showPopup(view);
}
};
public void showPopup(View v) {
Button b = (Button) view.findViewById(R.id.b_attach);
PopupMenu popup = new PopupMenu(getActivity(), b);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
//dosomething
}
});
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_popup, popup.getMenu());
popup.show();
}}
this is the way i do and it works for me:
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,new fragment() ).commit();
I solved the issue getting rid of sendbroadcast() and broadcastReceiver(), instead of that now I call showPopup() directly from the mainActivity when I need it.

What is going on with my Android Navigation drawer activity?

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.

Simple buttons to get Tab feature in android

I am trying to attain Tab feature using simple Buttons
What is happening now::
Click on Button1 ----> F1 Activity is displayed
Click on button1 (again) ---- > F2 Activity is isplayed
Click on Button1 (third time) -----> F1 Activity is Displayed
again
-
Similarly with Button2 w.r.t G1 & G2 activities
FragmentDemo.java
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
case R.id.button2:
state = !state;
if (state) {
addFragment(new G2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new G1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}
F1.java
public class F1 extends Fragment {
Context c;
View v;
public F1(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f1, container, false);
return v;
}
}
F2.java
public class F2 extends Fragment {
Context c;
View v;
public F2(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f2, container, false);
return v;
}
}
Similarly for G1 & G2
activity_fragment_demo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".FragmentDemo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2" />
</LinearLayout>
<LinearLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
OUTPUT::
Clearly we can see that, when i start the project i come to blank screen ..... A default activity is not displayed. As it does in Tabs
How can i make sure a default activity say F1 be already be present when i load the project
Like this ::
Any ideas
What changes should i need to make in the code
Hope i am clear
Your Layout activity_fragment_demo looks good so I will use that. The LinearLayout with id simple_fragment will be the container that holds the fragment's view
So lets say that the fragment F1 represents your first Tab and the fragment F2 represents your second tab.
So three methods that you should have are.
The following method adds each fragment to the activity and has to be called for both F1 and F2 in the activity's onCreate
public void addFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, fragment);
}
The following method essentially shows a fragment.I am not sure about the behind workings of attach but it can be seen as View.VISIBLE
public void attachFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportManager().beginTransaction();
ft.attach(fragment).commit();
}
The following method essentially hides a fragment.I am not sure about the behind workings of detach but it can be seen as View.GONE
public void attachFragment(Fragment fragment)
{
FragmentTransaction ft = getSupportManager().beginTransaction();
ft.detach(fragment).commit();
}
Your Activity's onCreate method
public void onCreate()
{
//Create all your fragments here eg F1 f1 = new F1(); etc
//For whatever fragment you have created you should call the method addFragment
//Now depending on what fragment you want shown by default you should call attachFragment or detachFragment. eg. if F1 has to be shown by default
attachFragment(F1);
detachFragment(F2) //and all otherfragment you want hidden by default
//Set the listeners for the buttons
//The purpose of the next two lines is to store the current state of the buttons. Since F1 is attached to button1 and it is currently being shown we set the tag to "clicked"
//and button2 tag has been set to notClicked
button1.setTag("clicked");
button2.setTag("notClicked");
}
Inside the onClickListener for your buttons
OnClickListener onTabButtonClickListener = new OnClickListener()
{
public void onClick(View view)
{
switch(view.getId)
{
case R.id.button1
{
if(button1.getTag().equals("clicked"))
{
detachFragment(F2);
attachFragment(F1);
button1.setTag("notClicked");
button2.setTag("clicked");
}
else
{
detachFragment(F2);
attachFragment(F1);
button1.setTag("clicked");
button2.setTag("notClicked");
}
}
case R.id.button2
{
//Same thing as before except opposite
}
}
}
}
And that should work.I am not very good at explaining stuff so feel free to ask any questions you have.
With the suggestion user1950599 in his comment he gave ..... i achieved this
just one line of updating was required
Sharing this might help someone
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(this);
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
case R.id.button2:
state = !state;
if (state) {
addFragment(new G2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new G1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}

Categories