How to replace a Fragment on button click of that fragment? - android

I have an activity containing multiple fragments. Activity initially have fragment and in it have two buttons. Upon clicking this button I have to replace the fragment by new fragment. Each fragment has various widgets and replace the current fragment as various events.
This is my problem. How can I achieve this?
Suggest me ideas.

you can replace fragment by FragmentTransaction.
Here you go.
Make an interface.
public interface FragmentChangeListener
{
public void replaceFragment(Fragment fragment);
}
implements your Fragment holding activity with this interface.
public class HomeScreen extends FragmentActivity implements
FragmentChangeListener {
#Override
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment, fragment.toString());
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
}
Call this method from Fragments like this.
//In your fragment.
public void showOtherFragment()
{
Fragment fr=new NewDisplayingFragment();
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.replaceFragment(fr);
}
Hope this will work!
NOTE: mContainerId is id of the view who is holding the fragments inside.
You should override Fragment's onString() method as well.

Well even I am learning android...
I solved same problem recently, "How to Change Fragment On button's click event".
buttonName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity()
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame1, new Homefragment());
fragmentTransaction.commit();
}
});
Here frame1 is id of FrameLayout which have define in my DrawerLayer's XML.
So now whenever I want fragment transaction I use this code. Each time it will replace frame1 instated of your last fragment.
FragmentTransaction fragmentTransaction = getActivity()
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame1, new newfragment());
fragmentTransaction.commit()
Hope this will help..

You can use the following to replace a fragment on button click of that fragment:
getFragmentManager().beginTransaction().replace(R.id.main_content, new insertFragmentNameHere()).addToBackStack(null).commit();

Define an interface and call it IChangeListener (or something like that) and define a method inside which will do the work (ex, changeFragment()) (or call another method which will do the work) for changing the fragment).
Make your activity implement the interface, or make an anonymous class within the activity implement it.
Make a paramerized constructor of your fragment, which accepts a IChangeListener parameter.
When initializing the fragment, pass your IChangeListener implementation (the anonymous class or the activity, implementing it)
Make the onClick listener of the button call the changing method of the IChangeListener.

From the future 2017 and after, there exists different libraries that triggers Events using Bus and now you can use it to tell the activity when an event is trigger in a fragment that it owns.
Refer to:
RxBus with RxJava
You can check new architectures suggested by Google
ViewModel
Don't use the approach in the accepted answer, get really ugly with more than 3 different events from fragments

you can try this code it's work fine with me , inflate the layout to view , Define the buton and on click ,
Button btn_unstable;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
btn_unstable = (Button)view.findViewById(R.id.btn_unstable);
btn_unstable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_replace, new UnstableFragment()).commit();
}
});
return view;
}

Related

Fragment button not opening new activity

I've incorporated a horizontal slide navigation component (which required making the class extend Fragment). The slide part works fine. Here i have respective onClick() buttons which open a new activity. If I add a button into one of those activities I'm not finding a way to have the displayed activity subsequently refresh. I would think inflating an activity from a button within a fragment would be possible but anything I try stops the emulator.
There's not much to my code so far, so I'm not going to clutter my question with the associated layout part. Any help is certainly appreciated.
Fragment #1’s Java code
public class TasksFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tasks, container, false);
Button ID = (Button) rootView.findViewById(R.id.button_create_appraisal_rpt);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppraisalReportActivity appraisalRptAct = new AppraisalReportActivity();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.child_fragment, appraisalRptAct);
fragmentTransaction.setTransition(fragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return rootView;
}
}
Fragment #1 (portion), which has the button that should initiate aa refresh of this Fragment #1 with Fragment #2
Fragment #2 that's to supersede/refresh the previous fragment when Fragment #1's button is clicked
I don't really understand what you mean. Do you want to click Button in Fragment to jump to another Activity?
If it is,I think maybe you can try use getActivity() to make Activity are working.
for example:
getActivity().startActivity(new Intent(getActivity(),Activity.class))
I hope my answer will help you

Connecting Fragments using ImageButton in Android

I'm new Android programming. Earlier I was working with activities, where i could implement onClick on an ImageButton and go to a different activity.
Now I need to do the same but using Fragments. I have a prototype with a menu that always appear on screen and can show different activities to the user. The different lactivities would be inside this container.
Now I want to place an ImageButton inside a fragment and make that the screen shows the next fragment. But I'm confused how to do it.
I have the following components:
Activity_main(java)+activity_main.xml (with menu)
Fragment1(java)+fragment1.xml(working normal)
Inside this layout I have an ImageButton and want to show Fragment2
Fragment2(java)+fragment2.xml
How should look Fragment1 to can call Fragment2?
I will be glad if the answer could be the clearest possible because I'm new on it, and maybe I could forgot an obvious step. Thanks
Simply make a method in your activity which will always change/replace fragment when you invoke it. something like
public void updateFragment(Fragment fragment){
//add fragment replacing code here
}
in your fragment, invoke it some thing like this
((YourActivity)getActivity()).updateFragment(new YourFragment());
since, it is just an idea which works fine but still you can improve the logic.
Actually, going from one fragment to another is almost similar to going from one activity to another. There are just a few extra lines of code.
First, add a new Java class named SingleFragmentActivity which would contain the following code-
public abstract class SingleFragmentActivity extends AppCompatActivity
{
protected abstract Fragment createFragment();
#LayoutRes
protected int getLayoutResId()
{
return R.layout.activity_fragment;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null)
{
fragment = createFragment();
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
}
Make your activities in the following format-
public class SomeActivity extends SingleFragmentActivity
{
#Override
protected Fragment createFragment()
{
return SomeFragment.newInstance();
}
}
And your fragments like this-
public class SomeFragment extends Fragment
{
public static SomeFragment newInstance()
{
return new SomeFragment();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
return v;
}
}
After this everything has the same code as you have for activities except for one small detail which is your onCreateView(LayoutInflater, ViewGroup, Bundle) class. This is how you would write it-
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
mTextView = (TextView)v.findViewById(R.id.some_text);
mButton = (Button)v.findViewById(R.id.some_button);
mTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
check();
}
});
return v;
}
And that is it!
Hi i hope you are already aware about the fragments and their uses but still here is a brief. They are child to an activity and an activity can have more than one fragment so you can update your layout without changing activity just by changing fragments.
You can found more on fragment here : https://developer.android.com/training/basics/fragments/index.html
Back to the original problem, supposed you are in MainActivity.java and you want to load fragment in it, so you do this to load fragment first time.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
You will need this method to change fragment from another fragment, so add this in your MainActivity
public void changeFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
}
Now from a button click in this fragment
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).changeFragment(new Fragment2);
}
});
Hope it will help!

how to access fragments elements in MainActivity()?

In my project, I want to set visibility of fragments buttons from MainActivity. But the problem is, it gives NullPointerException(). I also maked listBtn & gridBtn as static. I used below code :
FirstFragment fragment = (FirstFragment)getSupportFragmentManager().findFragmentById(R.id. <frameLayout Id>);
main_page_fragment.listBtn.setVisibility(View.GONE);
main_page_fragment.gridBtn.setVisibility(View.GONE);
You cannot access to your fragment view from Activity class because activity uses its own view (ex: R.layout.activity_main). Rather you can set visibility in your corresponding fragment class which will do the same job.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details, container, false);
Button listBtn = (Button)view.findviewById(R.id.listBrn);
Button gridBtn = (Button)view.findviewById(R.id.gridBrn);
listBtn.setVisibility(View.GONE);
gridBtn.setVisibility(View.GONE);
return view;
}
Fragment onCreateView callback is called after onCreate method of activity, so i think you have tried to get access from it. That views will be accessible only after onResumeFragments callback is called, you should perform your actions with fragments there.
Another tip is that you strongly should not call views of fragments directly like you did or via static reference to views that's the worst. You should avoid such dependencies on fragments inner implementation. Instead of it, better is create some method like setInitialState (the name depends on your business logic) and just call it from activity.
So result code:
In activity:
private FirstFragment fragment;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init fragment here
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
fragment.setInitialState();
}
In fragment:
//this will be called on fragment #onResume step, so views will be ready here.
public void setInitialState() {
listBtn.setVisibility(View.GONE);
gridBtn.setVisibility(View.GONE);
}
If you add your fragments dynamically from MainActivity like so:
YourFragment fragment = new YourFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, fragment, YOUR_TAG)
.commit();
Then you can define method in your fragment like so:
public void hideButtons()
{
yourBtn.setVisibility(View.GONE);
}
And call it from activity:
fragment.hideButtons();
I struggle with this for several hours and I found a much simpler solution.
Inside the fragment, simply make a public function (outside the on create view method) with the behavior that you want.
fun hideElement() {
binding.button.visibility = View.GONE
}
And then in main activity access to the fragment and call the function.
binding.bottomNavigation.setOnNavigationItemSelectedListener {
when (it.itemId){
R.id.someFragment -> someFragment.hideElement()
}
}

How can I maintain a child view's state when switching fragments?

I am having a hard time understanding how the fragment lifecycle relates to switching between fragments in the back stack. Please bear with me if my question exposes more than one misconception.
Here is my code:
public class SomeFragment extends Fragment {
private SomeCustomView customView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.some_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Create the child view
customView = (SomeCustomView) getView().findViewById(R.id.some_fragment_child_view);
customView.initializeMyCustomView();
}
}
As you can see, my fragment has a child view. The child view is a custom one. Here's code:
public class SomeCustomView extends SurfaceView implements SurfaceHolder.Callback {
private boolean aVariableWhichMustPersistForLifetimeOfApplication;
}
Whenever this fragment is added to the back stack and then later restored, the variable customView is recreated, and so I loose the value of aVariableWhichMustPersistForLifetimeOfApplication. This is creating all sorts of problems for me.
The application started out using an Activity that only displayed SomeCustomView and there were no fragments. Now I have to add functionality and so I have turned the custom view into a fragment, and thus I arrive at this problem.
I found an answer which works for me. The FragmentTransaction class has a number of methods which allow you to switch fragments in/out. (Android documentation for FragmentTransaction is here and a great StackOverflow explanation is here.)
In my case, I wanted SomeFragment to never loose the data contained in its view. To do this, use this code:
SomeFragment fragment = new SomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.activity_fragment_placeholder, fragment, "some_fragment");
transaction.commit();
and then later:
getFragmentManager().beginTransaction().hide(fragment).commit();
You can now add/attach a different fragment to R.id.activity_fragment_placeholder. Notice that I'm using hide() rather than replace(), that's the key difference that keeps the view from being destroyed. When you want the fragment back, you can use show() or Android will do this automatically when the user clicks "Back" if you use addToBackStack() when adding/attaching your other fragment.

New layouts in TabHost

I'm using tabHost in my application but in one of the views (corresponding to one of the tabs) I have a button that have to take me to another activity and then another layout. The question is: how do I get this new layout can continue to have access to the tabs? or better say, How do I load this new layout inside the FrameLayout ?.
Here I have uploaded what I'm trying to do: http://imageshack.us/photo/my-images/541/exampleu.png/
Thanks in advance.!
Pd: I'm new in Android, maybe is there a better way to achieve my purpouse without using TabActivity. I'm open to any suggestion.
EDITED: so I decided to use Fragments as I was suggested. And now I have the following:
AplicationActivity extends FragmentActivity
ClientActivity extends Fragment
SettingsActivity extends Fragment
DataClientActivity extends Fragment
and the following layouts:
activity_aplicacion
activity_client
activity_settings
activity_data_client
The activity_aplicacion.xml has TabHost, FrameLayout and TabWidget and from these I can go to ClientActivity and SettingsActivity using tabs.
In ClientActivity I have a button called "new" and when I press this button I want to go to
DataClientActivity. So, in ClientActivity I have te following:
public void onClickNew(View view){
DataClientActivity fragmentDataClient = new DataClientActivity ();
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.tabcontent,fragmentDataClient , "fragmentDataClient ");
ft.addToBackStack(null);
ft.commit();
}
But when I run my app, I got the folling error:
05-04 21:55:04.780: E/AndroidRuntime(7515): java.lang.IllegalStateException: Could not find a method onClickNew(View) in the activity class com.n.r.AplicationActivity for onClick handler on view class android.widget.Button with id 'buttonNew'
So I'm a little confuse rigth now. Why should I have the onClickNew method in AplicationActivity and not in ClientActivity where I have the button?
EDITED 2: I found the solution for this:
public class ClientActivity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.activity_clientes, container, false);
**// Register for the Button.OnClick event
Button b = (Button)view.findViewById(R.id.buttonNew);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
Log.e("onClickNuevo2 ", "inicio");
DataClientActivity fragmentDataClient= new DataClientActivity();
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.tabcontent,fragmentDataClient, "fragmentDataClient");
ft.addToBackStack(null);
ft.commit();
}
});**
return view;
}
}
I just needed to register the onClick listener to my button inside my ClientActivity. Now every works perfectly!. Thanks so much Divya Motiwala :) and thanks to this link: http://thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/#comment-410
You can use Fragments instead of activites inside Tab. And on click of button, you can replace existing fragment with a new one like this :
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.realtabcontent,newFrag, "New Fragment");
ft.addToBackStack(null);
ft.commit();
In ft.replace 1st parameter is the frameLayout to which fragment is to be attached, second is the fragment class object to be instatiated and third is the tag name.

Categories

Resources