adding same fragment more than once at runtime - android

i am designing an alarm application.
I am working with a fragment that acts as my alarms, the idea is to use the same one for each new alarm (i don't know if this is the right way).
Well, then i am basically trying to add, via pressing a "new alarm" button, the same fragment again into the layout of an activity, but when i press the button the app crashes. Any help?
I am inserting the fragment into a LinearLayout that is inside a ScrollView that is inside of the RelativeLayout
package com.example.roo.proyi;
import android.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class alarms extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarms);
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
final android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
alarm_fragment alarmFragment = new alarm_fragment();
fragmentTransaction.add(R.id.alarmListContainer,alarmFragment);
fragmentTransaction.commit();
Button button_newAlarm = (Button)findViewById(R.id.button_new_alarm);
button_newAlarm.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
alarm_fragment alarmFragment2 = new alarm_fragment();
fragmentTransaction.add(R.id.alarmListContainer,alarmFragment2);
fragmentTransaction.commit();
}
;
}
);
.
.
.
.
.
.CONTINUES BUT IT IS IRRELEVANT
.
.
.
FINAL SOLUTION MADE BY CREATING A DIFFERENT FRAGMENTTRANSACTION
public class alarms extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarms);
final android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
final android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
final alarm_fragment alarmFragment = new alarm_fragment();
fragmentTransaction.add(R.id.alarmListContainer,alarmFragment);
fragmentTransaction.commit();
Button button_newAlarm = (Button)findViewById(R.id.button_new_alarm);
button_newAlarm.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
android.support.v4.app.FragmentTransaction fragmentTransaction2 = fragmentManager.beginTransaction();
getSupportFragmentManager().beginTransaction();
alarm_fragment alarmFragment2 = new alarm_fragment();
fragmentTransaction2.add(R.id.alarmListContainer,alarmFragment2);
fragmentTransaction2.commit();
}
;
}
);

You cannot use the same FragmentTransaction to add the fragment inside of your OnClickListener. Once you call commit() on a transaction, you cannot use it again. Call getSupportFragmentManager().beginTransaction() to get a new transaction.

Check this code out -
1. It checks whether you have added a dialog fragment in the stack already or not. If yes, it will remove the fragment and add new fragment with a new argument, if it does not exist, it will add the fragment anyway.
see if you could incorporate this approach in your code -
void showDialog() {
mStackLevel++;
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");
}
Source is Android developer site

Related

Android Studio 3.6.1 error when i hook frame layout with autocomplete

Hello I just want to switch from a fragment to another using a button. Nothing difficult... the code works well but I have spent a lot of time because Android goesto error if I hook frameLayout with autocompile.
I'm explaining better:
package com.example.fragcookbook;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity {
FragmentOne mFragmentOne;
FragmentTwo mFragmentTwo;
int showingFragment=0;
#Override
protected void onCreate ( Bundle savedInstanceState ) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
mFragmentOne = new FragmentOne();
mFragmentTwo = new FragmentTwo();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frameLayout, mFragmentOne);
fragmentTransaction.commit();
showingFragment=1;
}
public void switchFragment(View view) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (showingFragment==1) {
fragmentTransaction.replace(R.id.frameLayout, mFragmentTwo);
showingFragment = 2;
} else {
fragmentTransaction.replace(R.id.frameLayout, mFragmentOne);
showingFragment=1;
}
fragmentTransaction.commit();
}
In all rows where you see R.id.frameLayout i have to handly write frameLayout..... Android colors it red but It works...
But if i choose the resource with autocompile...
...when i run app Android gives me this error....
Why? is not best practice use autocompile?
Thanks in advance
Try this may will help you.Go to "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.
Or
Restar you android studio and emulator

FragmentTransaction.replace() arguments

I created a class called SlidingFragment that extends from Fragment, and in my MainActivity I put these lines:
MainActivity.java :
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpView();
setUpFragment();
}
void setUpView(){
setContentView(R.layout.activity_main);
}
void setUpFragment(){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
SlidingFragment fragment = new SlidingFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
transaction.commit();
}
}
The problem is that the replace() method of the FragmentTransaction class can't recognize the second argument fragment which is a SlidingFragment object. I get this:
wrong second argument type found.'SlidingFragment' required 'android.support.v4.app.Fragment'.
replace(int,android.support.v4.app.Fragment)
to
replace(int,com.example.g514110.IhmSlidingTabs.SlidingFragment)
I understand the problem, but I don't know how to solve it.
Can someone please help.Thanks
Do that SlidingFragment extends
import android.support.v4.app.Fragment;
and not
android.app.Fragment
Make sure your SlidingFragment is extending android.support.v4.app.Fragment. Based on this compiler error, it currently is not.
Before I am also facing this issue , I did few changes . Now it's Workking Fine
New frgment page Eg : home_fragment
import android.support.v4.app.Fragment;
Main XML Design must contain any layout with your id eg :
android:id="#+id/fragment_container"
Main Java Class
import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
Click Event
home_fragment fragment = new home_fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
This Code Workking Fine For Me

How can i solve this errors and convert types?

I am a beginner in android programing. I want to write a program with fragment, i read this tutorial(http://www.mysamplecode.com/2012/08/android-fragment-example.html) and write that but when i run the program, the program has compiler errors!
The errors are about add() and replace() functions.
I write AndroidFragmentActivity class in below, Please read this and help me.
AndoridFragmentActivity.java:
package com.appfragmentarray;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.appfragmentarray.ListFragment.OnURLSelectedListener;
public class AndroidFragmentActivity extends Activity implements OnURLSelectedListener{
boolean detailPage = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("AndroidFragmentActivity", "onCreate()");
Log.v("AndroidFragmentsavedInstanceState", savedInstanceState == null ? "true" : "false");
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ListFragment listFragment = new ListFragment();
ft.add(R.id.displayList, listFragment, "List_Fragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
if(findViewById(R.id.displayDetail) != null){
detailPage = true;
getFragmentManager().popBackStack();
DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.displayDetail);
if(detailFragment == null){
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
detailFragment = new DetailFragment();
ft.replace(R.id.displayDetail, detailFragment, "Detail_Fragment1");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
}
public void onURLSelected(String URL) {
Log.v("AndroidFragmentActivity",URL);
if(detailPage){
DetailFragment detailFragment = (DetailFragment)
getFragmentManager().findFragmentById(R.id.displayDetail);
detailFragment.updateURLContent(URL);
}
else{
DetailFragment detailFragment = new DetailFragment();
detailFragment.setURLContent(URL);
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.displayList, detailFragment, "Detail_Fragment2");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
}
The errors are:
Cannot cast from Fragment to DetailFragment
The method add(int, Fragment, String) in the type FragmentTransaction
is not applicable for the arguments (int, ListFragment, String)
The method replace(int, Fragment, String) in the type
FragmentTransaction is not applicable for the arguments (int,
DetailFragment, String)
How can i solve this problems? Thanks.
You're probably mixing up the compatibility Fragments and the normal 3.0+ Fragment classes.
If you want to use the compatibility package:
Make AndroidFragmentActivity extend FragmentActivity
Change
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
to
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
and make sure all calls to getFragmentManager() are instead getSupportFragmentManager()
Make sure your Fragments extend from android.support.v4.app.Fragment instead of android.app.Fragment
OR
If you want to use the normal Fragments, get rid of all the support.v4 imports and make sure that your Fragments work with android.app.Fragment, which is the non-comptability Fragment.
It looks like you're mixing support library (v4) fragments with native fragments. Make sure ALL your fragments and related components are using v4. For example, your activity should be extending FragmentActivity instead of Activity. Make sure your ListFragment and DetailFragment also use v4 and not the native Fragments.
we should be sure if we are using compatibility or normal fragments, either android.support.v4.app.* or android.app.*
I am using android.support.v4.app.* and
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
and it works well for me..

Android app design with several fragments

I am trying to create a tablet application with fragments. The left part of the screen will have four buttons and the right part of the screen will change depending on what button was clicked.
I have created main activity and four fragments. Each fragment has its own layout with several TextView fields. When applications starts it loads all fragments to RAM - this way it can keep the fragments status so that when user switch from one fragment to another all the text fields keep their text values until he clicks the final submit button. The app is based on SDK 4.1. The app is a little bit slow especially when it starts. I was wondering if it has been designed properly and if there are some way to improve it?
Below is the main activity class:
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button buttonOne;
private Button buttonTwo;
private Button buttonThree;
private Button buttonFour;
private Fragment fragmentOne;
private Fragment fragmentTwo;
private Fragment fragmentThree;
private Fragment fragmentFour;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOne = (Button) findViewById(R.id.button_one);
buttonTwo = (Button) findViewById(R.id.button_two);
buttonThree = (Button) findViewById(R.id.button_three);
buttonFour = (Button) findViewById(R.id.button_four);
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
fragmentThree = new FragmentThree();
fragmentFour = new FragmentFour();
FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();
fragmentTransaction.add(R.id.frameLayout_one, fragmentOne);
fragmentTransaction.add(R.id.frameLayout_one, fragmentTwo);
fragmentTransaction.add(R.id.frameLayout_one, fragmentThree);
fragmentTransaction.add(R.id.frameLayout_one, fragmentFour);
fragmentTransaction.commit();
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();
fragmentTransaction.show(fragmentOne);
fragmentTransaction.hide(fragmentTwo);
fragmentTransaction.hide(fragmentThree);
fragmentTransaction.hide(fragmentFour);
fragmentTransaction.commit();
}
});
buttonTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();
fragmentTransaction.hide(fragmentOne);
fragmentTransaction.show(fragmentTwo);
fragmentTransaction.hide(fragmentThree);
fragmentTransaction.hide(fragmentFour);
fragmentTransaction.commit();
}
});
buttonThree.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();
fragmentTransaction.hide(fragmentOne);
fragmentTransaction.hide(fragmentTwo);
fragmentTransaction.show(fragmentThree);
fragmentTransaction.hide(fragmentFour);
fragmentTransaction.commit();
}
});
buttonFour.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();
fragmentTransaction.hide(fragmentOne);
fragmentTransaction.hide(fragmentTwo);
fragmentTransaction.hide(fragmentThree);
fragmentTransaction.show(fragmentFour);
fragmentTransaction.commit();
}
});
}
Consider using a FragmentStateViewPager.
In an ideal world, if you have several Fragments you are switching between like in your case, you'll probably not want to keep them around in RAM. 2 or 3 fragments is probably okay, 4 or more is starting to push it.
The FragmentStateViewPager will automatically detach and save the state of your Fragments as they move "off screen"
You will have to implement onSaveInstanceState in each one of your fragments to save any state of any non-UI member variables (UI Views save their state automagically). Then restore them in onCreate or onCreateView.
*Of course, if your Fragments' onCreate/onCreateViews are slow, then this won't help much. First make sure your Fragments' creations are fast... Start by looking for code that can be moved from onCreate/onCreate view to onResume.

How to implement show and hide fragment inside fragment in android

How to implement show and hide fragment inside fragment in Android? I have added two fragment inside activity. One fragment containing menu and one fragment contain sub menu. I have lot of button in menu fragment like home, idea, etc. If i click idea button. I have to show sub menu. If I again click idea button, I have to hide the sub menu. Can anybody provide example, or how to access one view fragment in another fragment?
this is my layout main
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<fragment class="com.gcm.fragment.CommonFragment"
android:id="#+id/the_frag"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<fragment class="com.gcm.fragment.SubFragment"
android:id="#+id/the_frag1"
android:layout_marginTop="130dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In My fragment
package com.gcm.fragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class CommonFragment extends Fragment implements OnClickListener {
TextView txtIhaveIdea=null;
boolean menuVisible=false;
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.collapsed_menu2, container, false);
txtIhaveIdea=(TextView)layout.findViewById(R.id.txtIhaveAnIdea);
txtIhaveIdea.setOnClickListener(this);
return layout;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!menuVisible)
{
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragOne = new SubFragment();
ft.show(fragOne);
}
else
{
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragOne = new SubFragment();
ft.hide(fragOne);
}
}
}
Thanks
You could try get framelayout or fragment by id and change its visibility
View frag = findViewById(R.id.my_fragment);
frag.setVisibility(View.VISIBLE);
Considering this question has over 2K .. an answer may still help new readers so here it goes:
You don't really want to have FragmentManager and FragmentTransactions happening inside fragments not to have Casts nor potential harmful references to your Activity(s)
So what I do and works just fine is set an interface to the Fragment and give a method, say needsHide():
public class MyFrag extends Fragment {
public interface MyFragInterface {
public void needsHide();
}
Then implement it on your Activity:
public class MainActivity extends FragmentActivity implements MyFrag.MyFragInterface {
public void needsHide() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//find the fragment by View or Tag
MyFrag myFrag = (MyFrag)fragmentManager.findFragmentByTag(SOME_TAG);
fragmentTransaction.hide(myFrag);
fragmentTransaction.commit();
//do more if you must
}}
The only part that requires thought is when to call needsHide(), this you might do in your Fragment's onViewCreated, since you are sure that it's not too early for your MainActivity to commit transactions. If you place it onCreate() it may not work depending on what you do with oter fragments:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Making sure Main activity implemented interface
try {
if (USE_A_CONDITION) {
((MyFragInterface)this.getActivity()).needsHide();
}
} catch (ClassCastException e) {
throw new ClassCastException("Calling activity must implement MyFragInterface");
}
super.onViewCreated(view, savedInstanceState);
}
Simply, create a public method in your "parent" activity. which hides the fragment.
Then from within the fragment in your click event get the "parent|' activity, cast it and then call the method you created.
((ParentActitity)getActivity()).hideFragment();
You need to use an Interface to communicate with your parent Activity.
Take a look on Vogella's tutorial, "3.4. Application communication with Fragments". Here is the link
method hide():Hides an existing fragment. This is only relevant for fragments whose views have been added to a container, as this will cause the view to be hidden.
your code :
#Override
public void onClick(View v) {
if(!menuVisible)
{
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
Fragment fragOne = new SubFragment();
ft.show(fragOne);
}
else
{
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fm.beginTransaction();
// it's wrong , you just hide the fragment that not added to FragmentTransaction
Fragment fragOne = new SubFragment();
ft.hide(fragOne);
}
}
Below code worked for me..
View frag = findViewById(R.id.fragment);
frag.setVisibility(View.GONE);//Or View.INVISBLE

Categories

Resources