Launch new activity from fragment in Android Studio [duplicate] - java

This question already has answers here:
android.content.ActivityNotFoundException:
(24 answers)
Closed 4 years ago.
i just want to open SkipActivity from MondayFragment, and fail in error. The swipe between fragments is work, but when i click on skip button move to another Activity- the app is crushed(closed):
All relevant code is attached, please help:
public class MondayFragment extends Fragment {
final String LOG_TAG="myLogs";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_monday, container, false);
TextView txt=(TextView) v.findViewById(R.id.skip);
txt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
//Start your activity here
Intent i = new Intent(getActivity(),SkipActivity.class);
startActivity(i);
}
});
return v;
}
}
This is java Activity class :
public class SkipActivity extends AppCompatActivity {
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.after_skip_scr);
}
}
This is MainActivity class - i think there is nothing to change here:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
}
}
Below is res-layout files: The first one is for monday fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/monday_main"
android:background="#a7cbeb">
<TextView
android:id="#+id/welcome_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_centerInParent="true"
android:textColor="#191970"
android:text="Welcome to Circles"
android:textSize="29sp"
/>
<TextView
android:id="#+id/skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="54px"
android:textStyle="italic"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginRight="25dp"
android:layout_marginTop="25dp"
android:text="skip"
android:textColor="#ffffff"
android:onClick="openSkipActivity"
/>
</RelativeLayout>
And this one is for main activity:
<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="MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

you can call activity by :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(), Contact_Developer.class);
getActivity().startActivity(intent);
}
});

why are you take this line
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
and share logcat error log.
or try this
decalare this
Context context;
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SkipActivity.class);
context.startActivity(intent);
}
});

Your app is crashing on click event because your view is null the reason is you are trying to find out the view by using activity.findViewById which will obvious return null.
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
Change above line with this
((TextView)v.findViewById(R.id.skip)).setText("Access from Monday Fragment");
After all you are launching activity from onClick event so doesn't make sense to update the text of skip textview. but if still you want to do that, no problem.
Just replace the above line of code, it should fix your issue.
As a suggestion in case you want to update the skip textview text in on click event or any other place, create a class level instance say TextView skipTextView and initialize in onCreateView then simply use skipTextView.setTex("<text>")" all over the place where ever required.

#Dima , Try this :
public class MondayFragment extends Fragment implements OnClickListener
{
final String LOG_TAG="myLogs";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_monday, container, false);
// Views
TextView txt=(TextView) v.findViewById(R.id.skip);
txt.setOnClickListener(this);
return v;
}
// onClick Method
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.skip:
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
Intent i = new Intent(getActivity(),SkipActivity.class);
startActivity(i);
break;
default:
break;
}
}
}

tnx for answers!
The problem was - i didn't declare the SkipActivity in manifest file.
At the moment i did it- the app is running and i can swipe between fragments and launch another Activity from fragment.
tnx a lot!

Related

Android Studio My Button on the second Activity doesn't Work

I think it a very easy Question. I am new to Android Studio and I could not find an answer.
I have an activity that switches per Button to another activity. However, on my second activity, my simple Button just to change the Textview which doesn't work.
Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".StartActivity">
<TextView
android:id="#+id/twText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="127dp"
android:layout_marginLeft="127dp"
android:layout_marginTop="88dp"
android:layout_marginEnd="127dp"
android:layout_marginRight="127dp"
android:layout_marginBottom="624dp"
android:text="Ihr Passwort war Richtig!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnChecke"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="134dp"
android:layout_marginLeft="134dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="189dp"
android:layout_marginRight="189dp"
android:layout_marginBottom="371dp"
android:text="Check"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
onCreate method in my second activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tw = findViewById(R.id.twText);
btnCheck = findViewById(R.id.btnChecke);
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tw.setText("work");
}
});
}
And this is how I am starting the second activity (onCreate method from my first activity).
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tw = findViewById(R.id.twText);
Button btnCheck = findViewById(R.id.btnChecke);
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView("Work"R.layout.activity_main);
}
});
}
I have checked the variable names in the layout and looks like everything is fine.
Thank you in advance.
This answer is based on the problem which I found before the latest edit from the OP. Here is the version of the edit where I found the problem.
First of all, something is very wrong about the onClickListener of your button. You are setting the content view again, instead of starting your second activity. It looks like, you are just setting the content view of your StartActivity which actually does not launch the MainActivity that you are trying to start.
In order to start a new activity, you need to add the following in your button onClickListener.
btnCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// setContentView(R.layout.activity_main); // This is not the way for starting another activity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
});
Once your MainActivity has started, you should be able to change the text with no problem.
Bundle bundle = getIntent().getExtras()
if(bundle.getString("changeTextView")
TextView .... = (TextView) ....setText();
Hi. If I good understand, you should use Intent with "putExtra()".
Exmple:intent.putExtras("changeTextView");
After that in your onCreate() method you can put:

How can i call fragment to activity?

I created a progress dialog into a fragment by using this effect. Now i must call it in different activities. When I call the effect the buttons at the background must not work. How can I do that?
First i need to learn how to call the fragment in a different activity. Then i must make the buttons at the background unclickable but there are many of them so ‘setclickabla(false)’ would be a tiring choice.
Progress Dialog Fragment XML:
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ProgressDialogFragment">
<com.skyfishjy.library.RippleBackground
android:id="#+id/ProgressDialogs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CB000000"
app:rb_color="#80FFFFFF"
app:rb_duration="2500"
app:rb_radius="32dp"
app:rb_rippleAmount="4"
app:rb_scale="6">
<ImageView
android:id="#+id/centerImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/logo" />
</com.skyfishjy.library.RippleBackground>
ProgressDialogFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_progress_dialog, container, false);
RippleBackground rippleBackground = (RippleBackground)view.findViewById(R.id.ProgressDialogs);
rippleBackground.startRippleAnimation();
return view;
}
For the buttons at the background to respond to clicks, you have to implement the onClick listener of the various buttons.
<com.skyfishjy.library.RippleBackground
android:id="#+id/ProgressDialogs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CB000000"
app:rb_color="#80FFFFFF"
app:rb_duration="2500"
app:rb_radius="32dp"
app:rb_rippleAmount="4"
app:rb_scale="6">
<Button
android:id="#+id/centerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/logo" />
In your layout above, you are making use of ImageView which I changed to centerButton and you can make it respond to clicks this way:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_progress_dialog, container, false);
RippleBackground rippleBackground = (RippleBackground)view.findViewById(R.id.ProgressDialogs);
rippleBackground.startRippleAnimation();
Button button=(Button)view.findViewById(R.id.centerButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// your respond to clicks
}
});
return view;
}
Call your fragment from your activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment fragment = new MainFragment(); // your fragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
}
}

How to refresh the data after click the item on listview for fragment

I have two fragments both AFragment and BFragment. The AFragment has a ListView. The BFragment has a Texview and a Button. The Afragment will change the fragment and putString to BFragment when the user clicked the item on ListView. The BFragment got the data from Afragment and display the date to TextView. How can I do?
The sample is like that
You can use libs https://github.com/greenrobot/EventBus . very easy!!!
EventBus in 3 steps
Define events:
public static class MessageEvent { /* Additional fields if needed */ }
Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Post events:
EventBus.getDefault().post(new MessageEvent());
You can use Interface and LocalBroadcastReceiver both for refreshing the Fragment.
Create one LocalBroadcastReceiver
LocalBroadcastManager.getInstance(context).registerReceiver(refreshFragment ,
new IntentFilter("refreshFragment"));
and its Method in BFragment
private BroadcastReceiver refreshFragment = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Do The Changes You Want To Refresh BFragment
}
};
And Than Call This LocalBroadcastReceiver in OnClick Event of the Button in AFragment.
Intent intent =new Intent("refreshFragment");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
You can do this by below approach without using external libraries:
Assume you've a MainActivity which hosts the two fragments FragmetA (which has a ListView) and FragmentB (which has the TextView)
Here's the full scenario:
Create an interface # FragmentB which will be used by MainActivity to know when a list item is selected
MainActivity will register a listener to FragmentA by overriding onAttachFramemnt() and implementing this interface
When the user selects a list item from FragmentA; FragmentB will trigger the callback back to MainActivity
MainActivity will forward the trigger to a public method in FragmentB which is used to set the text of the TextView to the current item.
Here is the code:
1. Layout
1.1 activity_main
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<fragment
android:id="#+id/fragment_b"
android:name="com.example.android.sendingdatafromfragmenta_to_fragmentb.FragmentB"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/fragment_a"
android:name="com.example.android.sendingdatafromfragmenta_to_fragmentb.FragmentA"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
1.2 fragment_a
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
1.3 fragment_b
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvSelectedItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Item selected" />
</LinearLayout>
2. Java
2.1 MainActivity
public class MainActivity extends AppCompatActivity implements FragmentA.OnListItemClickListener {
private static final String LOG_TAG = "LOG_TAG";
private FragmentB mFragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// inflating fragment B from xml
mFragmentB = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.fragment_b);
}
#Override
public void onAttachFragment(Fragment fragment) {
Log.i(LOG_TAG, "onAttachFragment");
super.onAttachFragment(fragment);
if (fragment instanceof FragmentA) {
((FragmentA) fragment).setOnListItemClickListener(this);
}
}
#Override
public void onListItemClick(String selectedITem) {
mFragmentB.setSelectedITemText(selectedITem);
}
}
2.2 FragmentA
public class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
final String[] data = {"item 1", "item 2", "item 3", "item 4", "item 5"};
ListView listView = view.findViewById(R.id.listView);
ArrayAdapter adapter = new ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mOnListItemClickListener != null) {
mOnListItemClickListener.onListItemClick(data[position]);
}
}
});
return view;
}
interface OnListItemClickListener {
void onListItemClick(String selectedITem);
}
OnListItemClickListener mOnListItemClickListener;
public void setOnListItemClickListener(OnListItemClickListener listener) {
mOnListItemClickListener = listener;
}
}
2.3 FragmentB
public class FragmentB extends Fragment {
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
public void setSelectedITemText(String text) {
TextView selectedItemTextView = view.findViewById(R.id.tvSelectedItem);
selectedItemTextView.setText(text);
}
}
Results

how to launch an activity from a fragment of a navigation drawer

I built a navigation drawer. When the app launches, I direct the user directly to "MainMenuActivity" activity from the MainActivity.
Inside the "MainMenuActivity", there is a button that should direct the user to another activity which is "Order List"; I applied two code parts but non is working:
The first code:
public class MainMenuActivity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_mainmenu, container, false);
Button Orderlistbtn = (Button) rootView.findViewById(R.id.orderlistbtn);
Orderlistbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainMenuActivity.this, OrderList.class);
startActivity(intent);
}
});
return rootView;
}
}
the app doesn't run, the first code gives me the following error in the logcat:
Error:(41, 33) error: no suitable constructor found for Intent(MainMenuActivity,Class<OrderList>)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; MainMenuActivity cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; MainMenuActivity cannot be converted to Context)
The second code:
public class MainMenuActivity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_mainmenu, container, false);
Button Orderlistbtn = (Button) rootView.findViewById(R.id.orderlistbtn);
Orderlistbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), OrderList.class);
startActivity(intent);
}
});
return rootView;
}
}
but the app crashes once it launches with the following logcat error
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{package/package.MainMenuActivity}: java.lang.ClassCastException: package.MainMenuActivity cannot be cast to android.app.Activity
this is "activity_mainmenu.xml" file:
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#android:color/background_light">
<Button
android:background="#ffff8800"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" My order list "
android:id="#+id/orderlistbtn"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
getActivity() in a Fragment returns the Activity the Fragment is currently associated with .
Intent intent = new Intent(getActivity(), OrderList.class);
startActivity(intent);
Edit
Secondly, You are getting ClassCastException
Thrown to indicate that the code has attempted to cast an object to a
subclass of which it is not an instance.
Use below code to call next activity, Hope this will solve your problem
Intent intent = new Intent((ParentActivity)getActivity(), NextActivity.class);
(ParentActivity)getActivity().startActivity(myIntent);

Android Fragment is not displayed

I'm quite new to Android dev and I followed the official Android's "Get started".
The fact is, my fragment is not displayed on the main activity ( it worked well few days ago but I changed some lines, I don't remember which ones ). I think it's a very basic problem as I don't use sophisticated fragments : it's basically one fragment inside an activity.
This is my activity :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mysecond.MainActivity"
tools:ignore="MergeRootFrame" />
My fragment :
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
And the java code for this activity (I have some other activities in the app, based on the same pattern "one fragment inside one activity" and they work well...)
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container1, new PlaceholderFragment()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Any ideas ?
Thank you :)
[edit]
so this is my new onCreate method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().replace(
R.id.container1, new PlaceholderFragment()).commit();
}
Still not working for this activity (If I add a button in activity_main.xml I'll be able to see it but the I'm not able to see the TextView in the fragment...)
No errors in logcat and yes the activity is launched (I added some Log.e in onCreate and onCreateView and I cas see them)
In your onCreate methode you don't have to check if the savedInstanceState is null but if the the content of the FrameLayout you use is null
Or you simply always replace the fragment with a new one and ommit any checking.
Instead of add, you can use replace.
You can do it like below shown code:
getSupportFragmentManager().beginTransaction().replace(
R.id.container1, new PlaceholderFragment());
For me this work. Implementa a interface FragmentActions with the init() method and use this
private void showFragment(String fragmentTag){
FragmentTransaction trasaction = getSupportFragmentManager().beginTransaction();
FragmentActions fragment = (FragmentActions) getSupportFragmentManager().findFragmentByTag(fragmentTag);
if(fragment==null ){
if(lastFragmentviewed!=null)
trasaction.hide(lastFragmentviewed);
fragment = (FragmentActions) newInstance(fragmentTag);
trasaction.add(R.id.content_frame,(Fragment) fragment,fragmentTag);
}else{
if(lastFragmentviewed!=null && !lastFragmentviewed.equals(fragment))
trasaction.hide(lastFragmentviewed);
if(getSupportFragmentManager().findFragmentByTag(fragmentTag)!=null){
fragment.init();
trasaction.show((Fragment) fragment);
}else
trasaction.add(R.id.content_frame,(Fragment) fragment,fragmentTag);
}
lastFragmentviewed=(Fragment) fragment;
trasaction.commit();
}

Categories