I follow this tutorial to create a viewpager gallery http://www.androidbegin.com/tutorial/android-viewpager-gallery-images-and-texts-tutorial/.
I added a onClick listener to the ImageView in the PagerAdapter.
I want to open a fragment when the imageview is clicked. How can I do that?
public void onClick(View v) {
// TODO Auto-generated method stub
transaction = getFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.frameContent, new TravelogueFragment()).commit();
}
I alreary tried that code inside my class which extend PagerAdapter but Im getting an error with the getFragmentManager() it says that getFragmentManager is undefine.
You have to use interface and listener. You can see code here. In my case, I replace Fragment when list item click, so you'll only need to adapt it and it will work.
Related
I tried to add a fragment on button click action inside an adapter which extends a BaseAdapter.
But to use fragments the class has to extend Fragment to use the FragmentManager.
I've imported :
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
But still facing an error here:
FragmentManager fragmentManager=getFragmentManager();
I've also tried to give the activity reference when getting the FragmentManager,it gave more errors.
Any help would be much appreciated.
Thanks in advance.
Here is my adapter code:
Drawer item(view) onclick action:
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position == 1)// Home
{
Home2Fragment fragment = new Home2Fragment();
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.add(fragment, null);
fragmentTransaction.commit();
}
}
});
Because importing Fragments from support library so, use getSupportFragmentManager method to get FragmentManager :
FragmentManager fragmentManager=<Activity_Context>.getSupportFragmentManager();
Need to use FragmentActivity context to access FragmentManager and also make sure extending FragmentActivity instead of Activity.
It is considered good practice to use let Adapters be an inner class of the List that uses them. That gives the adapter full access to the class using them and if it's a fragment, you can use the fragment manager.
I have an activity with a relative layout; And have two different fragments. I show one fragment and switch to the next fragment on a button click vice verse.
// When button menu is clicked
OnClickListener btnClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentType==0){
InitThisFragment(1);
}else{
InitThisFragment(0);
}
}
};
public void InitThisFragment(int type){
Fragment newFragment;
if(type==0){
newFragment=new MainFragment();
}else{
newFragment=new JourneyFragment();
}
currentType=type;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
R.id.abs_fragment_container is a Relative Layout
BOTH THE FRAGMENT CONTAIN GOOGLE MAPS INSIDE THEM;
But it is not working as expected.
By default i add the first fragment [which works fine].
Then after an onClick event the 2nd fragment comes[which also works
fine]
But on my next click the app crashes;
Please help I am new to Google Maps and Fragments;
yeah of course your app crashes because the fragment with the map already exists look at this thread it helped me a lot: Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment
Especially the second answer with 41 ups is easy to understand
And yes I would have posted this one in a comment if I would have enough reputation for it!
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;
}
I am new to fragment concept. In my app I have to save user preferences. I have gone through this doc.
Prepared my preferences xml file and PreferenceFragment file. Everything is fine up to now.
My problem is, I have to add the following code in my onCreate() method of my MainActivity
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
It is showing on Main screen. But I want to launch this on a button click method
onSettingsClicked(){
// launch preferces screen
}
And I want to display it as a separate screen. How can I do that?
You need to implement the concept of fragmentTransaction.
You need to do the following things-
Create a new Fragment.xml to display the button.
Invoke the new fragment from the onCreate();
Get the Button on the Fragment view.
On Button onclick listener replace the the fragment with the SettingFragment().
Done!
Check out this FragmentTransaction Tutorial, it will guide you-
Do the following changes like -
// Code not accurate, may be some syntax error
#Override
public void onCreate()
{
// super and other stuff
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new NewFragment())
.commit();
Button btn = (Button)findViewById(R.id.button01);
btn.setOnClickListener(new OnClickListener(){
#override
public void onClick(View v)
{
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new new SettingsFragment())
.commit();
}
});
}
Instead of using fragementTransaction you can use preferenceFragement :
How do you create Preference Activity and Preference Fragment on Android? by WannaGetHigh
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.