Start a fragment via Intent within a Fragment - 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

Call Fragment B from Fragment A using ViewPager Tabs

I have done many programs, where I have implemented multiple Fragments inside a Single Activity, but not when using Single Activity to host multiple Fragments as Tabs and then on Tap show another Fragments...
Using MaterialViewPager library, in which I am calling different different Fragments to show views in their respective Tabs.
Like For the First Tab, I am using two Fragments, where
In First Fragment, I am using RecyclerView... to show list of Menus.
And in Second Fragment, I am using RecyclerView... to show list of Items under particular Menu.
So here my question is How to call Fragment from Fragment.
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), mRecyclerView ,new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Value value = valueList.get(position);
List<Learning> learning = value.getLearning();
// using when putting "item" data into same recyclerview
// but on back press just exiting, not showing list of Menus again
/**
learningAdapter = new LearningAdapter(learning, R.layout.card_learning, getActivity());
mRecyclerView.setAdapter(learningAdapter);
**/
ItemFragment fragment = new ItemFragment();
replaceFragment(fragment);
}
Method replaceFragment
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// using Fragment not Activity, so where can I use frame_container in xml
transaction.replace(R.id.frame_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
you can have a callback interface that is implemented by the activity which hosts these two fragments. Fragment A will use the call back to notify the activity to replace A with fragment B. Depending on your need, you can pass parameters across through the callback method itself.
Your callback interface:
public interface YourCallback {
public void methodWhichReplacesFragmentAwithB(params...);
}
Your Activity hosting fragments:
public class YourActivity extends ... implements YourCallback {
..
..
#Override
public void methodWhichReplacesFragmentAwithB(params...) {
//insert replace fragment code here
}
}
Your fragment will have a callback object, YourCallback callbackObj;. This callback object can be initialised using the activity (pass as this from activity) itself since the activity has the implementation of the interface. Now, you can use
callbackObj.methodWhichReplacesFragmentAwithB(actual_params...);
to replace the fragment. This callback interface can be exploited for other communications to parent Activity as well as other fragment hosted in that activity.
To replace fragment,
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, someFragment).addToBackStack("null").commit();
You can try this:
YourFragment fragment = new YourFragment();
FragmentTransaction transaction = ((AppCompatActivity) mContext).getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
There is One option which i have been using from long time before. I will added the solution with clear example.
So you want to pass the value from fragment A to fragment B
So, here what you want to do is, you have pass the value through the activity.
1) you pass the value from fragment A to activity
2) then activity to fragment B
Step 1: first create an Interface Like below in fragment A
public interface HomePage {
void onHomeButtonsClicked(String clickedButton);
}
public void setOnHomeButtonClicked(HomePage homePage) {
this.homePage = homePage;
}
Step 2: then create the instance like below in Activity. where fragment created in PagerAdapter
((FragmentA) fragment).setOnHomeButtonClicked(new FragmentA.HomePage() {
#Override
public void onHomeButtonsClicked(String buttonClicked) {
pageSelected.onHomeButtonsClicked(selectedPage);
}
}
});
Step 3: then create the interface in Activity like below.
public interface PageSelected {
void onHomeButtonsClicked(String clickedButton);
}
public void setOnHomeButtonClicked(PageSelected pageSelected) {
this.pageSelected = pageSelected;
}
step 3: then add the following method in fragment B in onCreateView or onResume()
((MainActivity) getActivity()).setOnHomeButtonClicked(new MainActivity.PageSelected() {
#Override
public void onHomeButtonsClicked(String clickedButton) {
//fragment B received the value here
}
});
Step 5: finally add the line in fragment A in button click or where you want to pass the value.
homePage.onHomeButtonsClicked("Some String , by this code it is in String. you can change in your own data type");
You can rise your question if you face any difficulties.

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 use Intent method in CustomAdapter to Project_Fragment [duplicate]

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

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