How to use Intent method in CustomAdapter to Project_Fragment [duplicate] - android

I want to launch a new fragment to view some data. Currently, I have a main activity that has a bunch of actionbar tabs, each of which is a fragment. So, within a tab fragment, I have a button, chartsButton. I have my onclicklistener all set for it, and here's the onClick method:
public OnClickListener chartsListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent chartFragment = new Intent();
startActivity(chartFragment);
}
};
Now, as I said, this listener is within a class that extends Fragment. So, I want to launch a new fragment (chartsFragment) via the intent to replace the whole screen. When the user clicks back, it'll bring them back to the tabs and main activity. Here's my chart fragment:
public class chartsFragment extends Fragment {
public View onCreateView() {
//LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return (inflater.inflate(R.layout.chartfragment, null));
}
}
The current error I am dealing with: "android.content.ActivityNotFoundException: No Activity found to handle Intent { }". That's fine, I understand that I could use getActivity().startActivity(chartsFragment), but that results in the same error. I suppose what I am looking for here, is how do I launch an intent from within a fragment that results in opening a new fragment?

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
http://developer.android.com/guide/components/fragments.html#Transactions

You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.
So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

Try this it may help you:
public void ButtonClick(View view) {
Fragment mFragment = new YourNextFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}

Try this it may help you:
private void changeFragment(Fragment targetFragment){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}

try this:
in SecondActivity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtra("openFragment", "YourFragment");
startActivity(intent);
}
});
In the FisrtActivity that contains the fragment:
if (getIntent().getStringExtra("openFragment").equals("YourFragment")){
getSupportFragmentManager().beginTransaction().replace(R.id.containerView, new YourFragment()).commit();
}

Related

Activity to Fragment on button click

I have navigation bar on my app. Using that has created fragments. I added regular activities to the app and I have found how to go from a Fragment page to an activity page with using the onclick method.
By the click of a button I want to go from an activity page to a fragment page. How do I go about that?
Thank you
apply on click listner on the button and apply below code :-
Fragment fragment = new VehiclesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment).commit();
If you want to close the current activity to go back to your Fragment-container Activity you may call the finish() method or onBackPressed() method (in case you're not overriding it).
If you want to bring a fragment to the current activity you must have a fragment container and attach it with:
getSupportFragmentManager().beginTransaction.add(R.id.container, fragment, TAG).addToBackStack().commit();
Try this code..
btn.setOnClickListener(new View.OnClickListener()){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),FragmentTest.class);
getActivity().startActivity(intent);
}
});
If you want to move around in fragment then you have to be using either navigation bar clicks on tabs or use this from one fragment to another on a click of button .. like this
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = Fragment.instantiate(MainActivity.this, <name of the fragment>);
Bundle bundle = new Bundle();
bundle.putBoolean(ALL_EVENTS, true);
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
Simply use this:
Intent(view.context, DestinationActivity::class.java).also {
view.context.startActivity(it)
}

How to open fragment on a button click from an activity either with intent and without intent in android? [duplicate]

This question already has answers here:
How to open a Fragment on button click from a fragment in Android
(3 answers)
Closed 6 years ago.
I tried the following code:
Intent in= new Intent(Activity1.this,Fragment.class);
startactivity(in);
This is not how fragments work, fragments must be attached to an Activity. To get your desired effect you must either start a new Activity that contains the fragment you wish to show, or display the new fragment in the current Activity.
In order to decide between which approach to take, I would consider how you want the Fragment to affect the navigation of your interface. If you want the user to be able to get back to the previous view by using the Back button, you should start a new Activity. Otherwise you should replace a view in your current Activity with the new Fragment.
Though, it is possible to add a Fragment to the back stack, I would only attempt to do so if you are confident with the structure of your user interface.
To show a new fragment in the current Activity you can use a FragmentTransaction:
Fragment fragment = CustomFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_layout, fragment).commit();
write this code in your onCreate or in your intent:
FragmentManager fm = getSupportFragmentManager();
YourFragment fragment = new YourFragment();
fm.beginTransaction().add(R.id.main_contenier,fragment).commit();
Fragments not Open through Intent.
You should use Fragment manager.
Fragment fragment= new YourFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment); // fragment container id in first parameter is the container(Main layout id) of Activity
transaction.addToBackStack(null); // this will manage backstack
transaction.commit();
Sample Example of Fragment
public class MyFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_my, container, false);
Button button1= (Button) view.findViewById(R.id.button1_Id);
Button button2= (Button) view.findViewById(R.id.button2_Id);
return view;
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment= new YourFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment); // fragmen container id in first parameter is the container(Main layout id) of Activity
transaction.addToBackStack(null); // this will manage backstack
transaction.commit();
}
});
}

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

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;
}

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.

Start a fragment via Intent within a Fragment

I want to launch a new fragment to view some data. Currently, I have a main activity that has a bunch of actionbar tabs, each of which is a fragment. So, within a tab fragment, I have a button, chartsButton. I have my onclicklistener all set for it, and here's the onClick method:
public OnClickListener chartsListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent chartFragment = new Intent();
startActivity(chartFragment);
}
};
Now, as I said, this listener is within a class that extends Fragment. So, I want to launch a new fragment (chartsFragment) via the intent to replace the whole screen. When the user clicks back, it'll bring them back to the tabs and main activity. Here's my chart fragment:
public class chartsFragment extends Fragment {
public View onCreateView() {
//LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return (inflater.inflate(R.layout.chartfragment, null));
}
}
The current error I am dealing with: "android.content.ActivityNotFoundException: No Activity found to handle Intent { }". That's fine, I understand that I could use getActivity().startActivity(chartsFragment), but that results in the same error. I suppose what I am looking for here, is how do I launch an intent from within a fragment that results in opening a new fragment?
The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.
#Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
http://developer.android.com/guide/components/fragments.html#Transactions
You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.
So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.
Try this it may help you:
public void ButtonClick(View view) {
Fragment mFragment = new YourNextFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}
Try this it may help you:
private void changeFragment(Fragment targetFragment){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
try this:
in SecondActivity:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, FirstActivity.class);
intent.putExtra("openFragment", "YourFragment");
startActivity(intent);
}
});
In the FisrtActivity that contains the fragment:
if (getIntent().getStringExtra("openFragment").equals("YourFragment")){
getSupportFragmentManager().beginTransaction().replace(R.id.containerView, new YourFragment()).commit();
}

Categories

Resources