Replace Fragment from OnClickListener - java

I'm running into trouble. I have a Fragment with an onclicklistener. The fragment calls "ClickMe" which is in my Activity that hosts the fragment. However, in order for ClickMe to not error out, ClickMe has to be static. But, Clickme can't be static because then getFragmentManager errors out. Essentially I'm trying to create a game. A click will put a new fragment over the top of the old one (as you have to do the same thing 10 times in a row in my game. Here's the code:
Fragment:
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(loc1 == 10 || loc2 ==10){
//Text if user wins
BlankFragment.counter ++;
BlankFragment.ClickMe(BlankFragment.counter);
Log.i("Win: ", "Yay");
}else{
//Text if user loses
Log.i("Lose: ", "Boo");
}
}
});
MainActivity:
public void ClickMe(int count){
Fragment newFragment;
counter = count;
if(counter > 5){
newFragment = new g3by3Fragment();
}else{
newFragment = new g3by3Fragment();
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
Thank you for your help!

You don't have to preform FragmentTransactions from the Activity. You can just add well preform them from the Fragment. Your detour into the Activity through ClickMe is unnecessary. I know you probably do this because the logic of your game is in the Activity but that is not optimal. Let the Fragments themselves decide which Fragment comes next or implement a Singleton which takes care of your game logic.

Related

Disable onBackPressed only in ONE fragment - Android

Im trying with no success to disable the back key only in one fragment, in the first one.
I did the override of the onBackPressed method on the Activity that contains the fragment with this:
#Override
public void onBackPressed() {
if (this.fragmentManager.getBackStackEntryCount() > 1) {
//getFragmentManager().popBackStack();
super.onBackPressed();
} else {
//super.onBackPressed();
}
}
So, it works perfectly. BUT when i finish all the path of fragments, at the final fragment i have a button that take me back to the first fragment. I will paste the code where i load this fragment again.
for (Fragment fragment1:getSupportFragmentManager().getFragments()) {
getSupportFragmentManager().beginTransaction().remove(fragment1).commit();
}
MontoFragment montoFragment = new MontoFragment();
cargarFragment(montoFragment);
And here the "cargarFragment()" method
public void cargarFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.animation_slide_in,R.anim.animation_slide_out);
fragmentTransaction.replace(R.id.layoutContenedorFragments,fragment);
fragmentTransaction.addToBackStack(null).commit();
}
After i complete all the fragments and i go back to the first one with that, my onBackPressed method doesnt work anymore, because this.fragmentManager.getBackStackEntryCount() > 1 now is 5 or 6 i dont remember now. And this make the back key enable.
So i dont know what to do.
Thanks!
I just achieve it with this code
#Override
public void onBackPressed() {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.layoutContenedorFragments);
if (currentFragment instanceof MontoFragment){
}else{
super.onBackPressed();
}
}
i got the current fragment and if this one is an instanceOf That Fragment just do nothing but if not just do the normal onBackPressed.
I look that it works great
try to use popBackStack, replace code block:
for (Fragment fragment1:getSupportFragmentManager().getFragments()) {
getSupportFragmentManager().beginTransaction().remove(fragment1).commit();
}
MontoFragment montoFragment = new MontoFragment();
cargarFragment(montoFragment);
by
void popFragments(int number) {
for (int i = 0, i < number, i++) {
supportFragmentManager.popBackStackImmediate()
}
}
number here is the number of fragments you want to remove, ex: we have fragment 1,2,3,4, so when we are in fragment 4 and want to back to fragment 1, so the number will be 3.

How to run CountDownTimer in Fragment

I have one User Activity class which has drawer menu (includes home page, my profil etc..). When user clicks the one of the menu item, I will load fragment such as HomePageFragment, MyProfilFragment etc..
Here is the code example:
public void navigationItemSelectedListener(DrawerLayout drawerLayout, NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(menuItem -> {
menuItem.setChecked(true);
int menuId = menuItem.getItemId();
switch (menuId){
case R.id.home_menu_item:
loadFragment(new HomePageFragment());
break;
// goes like that
Here is the loadFragment:
public void loadFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.user_page_activity_frame_layout, fragment);
fragmentTransaction.commit();
}
}
Now I have run CountDownTimer(60 seconds) in HomePageFragment, when counter is 0, I will run some methods().
However I can not do that. Because each time user navigates new item, then when back to the HomePage menu item, new HomePageFragment() is creating, therefore CountDownTimer starts with 60s again and again. What I want CounDownTimer to run even if user navigates another menu.
Note that, I had tried to create HomePageFragment attribute as global. But it didn't work. (Like 2 timer counts down. One says 60-59... another says 30-29 ...)
Problem here is, your Fragment gets destroyed every time user navigates to another item.
To solve this
1.Either Create the Timer in your host activity instead the fragment, maybe inside navigationItemSelectedListener()
2.Make sure your fragment doesn't get destroyed everytime. Check How to resume Fragment from BackStack if exists

Removing/replacing fragments

I'm starting to work with fragments and ran into a problem. I have file viewing fragments(more than one) and a search fragment. To make things easier I add my file viewing fragment to backstack whenever I go to search so I could easily pop it back if I decide to just close it. Now the problem is that when I press on file in the search fragment so that I travel to the specific fragment in which that file is, the onCreateView of the first fragment(which was in backstack) always gets called even though I replaced it(?) and I don't want that. Here are things I do to change the fragments on search file press:
1.I call pop to get to previous fragment
#Override
public boolean onSearchViewClose() {
if (getActivity() != null) {
getActivity().getSupportFragmentManager().popBackStack();
return true;
}
return false;
}
2. Then I replace the remaining fragment
public void setFragment(Fragment fragment, String tag, boolean clearBackStack, boolean addToBackStack) {
// Insert the fragment by replacing any existing fragment
hideLoadingProgress();
FragmentManager fragmentManager = getSupportFragmentManager();
if (clearBackStack) {
clearBackStack(fragmentManager);
}
FragmentTransaction transaction = fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, tag);
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}
while clearing backstack:
public void clearBackStack(FragmentManager fragmentManager) {
for (int i = 0; i < fragmentManager.getBackStackEntryCount(); ++i) {
fragmentManager.popBackStack();
}
}
Even if I don't clear backstack the problem persists.Thanks for your answers in advance.
The answer was simple - I should've just used getActivity().getSupportFragmentManager().popBackStackImmediate(); when exiting search view as the earlier method didn't work because it waited for program to return to its event loop (asynchronous).

How to restart google map fragment manually

When the map fragment opens for the first time it calls onMapReady and it adds a marker in there and zooms towards with animation.
I want if user click a button on the map, the map will restart as if its open like the begining with zoom and whatnot.
I tried using the method below which I call when I click the button, but it only recreate the map but it didn't call onMapReady because it didn't add maker or anything.!
public void reLoadFragment(Fragment fragment) {
Fragment currentFragment = fragment;
if (currentFragment instanceof MapTransportFragment_BusDriver) {
FragmentTransaction fragTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
}
}
Edit #1
I call the method using all three ways belowa and it gives me the same error.
/*1*/ reLoadFragment(this);
/*2*/ reLoadFragment(MyMap.this);
/*3*/ reLoadFragment(new MyMap()); // MyMap is the name of the current fragment.
However, If you want just to restart your fragment it means you want to create new fragment. calling detach and attach doesn't destroy fragment.So try below code
public void reLoadFragment(Fragment fragment) {
Fragment currentFragment = fragment;
if (currentFragment instanceof MapTransportFragment_BusDriver) {
FragmentTransaction fragTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragTransaction.replace(R.id.YourFragmentContainer,currentFragment,"TAG");
fragTransaction.commit();
}
}

onBackPressed() not working while coming from another activity

I have three activities: First, Second and Third. I used this method in Second activity:
public void onBackPressed() {
super.onBackPressed();
finish();
}
and this on Third activity:
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent(Third.this, Second.class);
startActivity(i);
finish();
}
The problem is when I press back button after coming from the Third activity, I am going into First activity instead of finish(). I am successfully exiting the application when I click back button right after coming from first activity but not after coming from Third activity.
How to solve this problem?
EDIT: Thanks for the answers guys,the answer of "Ved Prakash" solved the problem for me.But i have a weird problem now.When i press back button the app is successfully exiting but the app which i minimized to Recent Apps button is coming on to the screen and exiting.For example,if i have opened Setting app before opening my app,when i press back button,my app is exiting and immediately Settings app is also opening and exiting itself.What might be the problem?
Your problem is that you don't seem to understand how Activities work. The finish() function ends the current Activity, and then you receive the previous Activity from the backstack.
My recommendation is that you should use a single Activity, and hold Fragments inside it. If you want it so that pressing the Back button ends the application at any screen that is displayed, you could do the following:
Activity XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/initial_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity that holds the Fragments:
public class InitialActivity extends FragmentActivity implements ReplaceWith
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_initial);
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
public void onBackStackChanged()
{
int backCount = getSupportFragmentManager().getBackStackEntryCount();
if (backCount == 0)
{
finish();
}
}
});
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction().add(R.id.initial_container, new FirstFragment()).commit();
}
}
#Override
public void replaceWith(Fragment fragment)
{
getSupportFragmentManager().beginTransaction().replace(R.id.initial_container, fragment).commit();
}
}
Example for a Fragment:
public class FirstFragment extends Fragment implements View.OnClickListener
{
private ReplaceWith activity_replaceWith;
private ImageView exampleImage;
public FirstFragment()
{
super();
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
activity_replaceWith = (ReplaceWith) activity;
}
catch (ClassCastException e)
{
Log.e(getClass().getSimpleName(), "Activity of " + getClass().getSimpleName() + "must implement ReplaceWith interface!", e);
throw e;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
exampleImage = (ImageView) rootView.findViewById(R.id.fragment_first_example_image);
exampleImage.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v)
{
if(v == exampleImage)
{
activity_replaceWith.replaceWith(new SecondFragment());
//please note that this should be done only if you are planning
//only on single-screen applications
//with no other layouts based on orientation or size
//otherwise, the Activity needs to be responsible for this, not the Fragment
}
}
}
This way, when you press the Back button, your application would end from any displayed screen.
Ok your code is wrong.
If you will look at activity source, you see that activity.onBackPressed() is calling finish(). So if call super.onBackPressed() you don't need to call finish.
Finish() is not stopping your application, it's stopping current activity.
Your code on third activity very strange. You are trying to stop activity and start another same activity.
What exactly you want to achieve?
If you want to exit application from your third activity, you need to clear your backstack. But I think you have problem with structure of your app.
Ok. then you should finish your first activity when you go to second activity like this(If you are using intent for that):
Intent it=new Intent(FirstActivity.this,SecondActivity.class);
finish();
startactivity(it);
and same for Second Activity:
Intent it=new Intent(SecondActivity.this,ThirdActivity.class);
finish();
startactivity(it);
this done your work...when you are in third activity the above activities are finished..
and when you press backButton you will be exit from application..
Good luck.
You can use -
public static final int FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the
current task, then instead of launching a new instance of that
activity, all of the other activities on top of it will be closed and
this Intent will be delivered to the (now on top) old activity as a
new Intent.
And here is how -
When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "MainActivity".
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
This explanation part is also introduced at exit-an-android-app.

Categories

Resources