Android ActionBarSherlock Fragment - android

I've been trying to get ActionBarSherlock working with Google's fragment tutorial and run into a problem when trying to add the "content" fragment to the view. This line produces the following exception
getFragmentManager().beginTransaction().add(android.R.id.content, content).commit();
The method add(int, Fragment) in the type FragmentTransaction
is not applicable for the arguments (int, ContentFragment)
The code is identical to Google's (http://developer.android.com/guide/components/fragments.html) except I've extended to SherlockActivity where needed. ContentFragment/Activity is merely what I've called Details activity.
Even if I take out all of the ABS references to make it a normal example, I get the same problem. I have a feeling its to do with the android support library, but I cant for the life of me figure it out.

Use getSupportFragmentManager() instead of getFragmentManager().

How does your fragment class look like? This code works fine for me:
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
FragmentADetail frag = new FragmentADetail();
ft.replace(android.R.id.content, frag);
ft.addToBackStack(null);
ft.commit();
And my FragmentADetail class looks like this:
public class FragmentADetail extends SherlockFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View v = inflater.inflate(R.layout.fragment_a_detail_layout, container, false);
v.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//left empty on purpose to capture the onClick event.
}
});
return v;
}
#Override
public void onStop()
{
super.onStop();
getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
}

Related

Remove Fragment in FragmentTransaction cannot be applied to

I am having and issue about closing a Fragment.
The reason why I cannot close the Fragment, within the customized Fragment itself, with the following chaining
getActivity().getFragmentManager().beginTransaction().remove(this);
seem to be inheritance, since my customized Fragment inherits from ..
extends android.support.v4.app.Fragment
Android Studio is complaining about the argument in remove(), - "this"
remove (android.app.Fragment) in FragmentTransaction cannot be applied to se.fragmenttest.app.myfrafmentest180406.MyFragment)
The strange this is that the same call seem to work from within MainActivity where the Fragment is instanciated.
the whole class
public class MyFragment extends android.support.v4.app.Fragment {
private View fragmentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containter, Bundle savedInstanceState) {
fragmentView = inflater.inflate(R.layout.fragment_layout, containter, false);
Button button = (Button) fragmentView.findViewById(R.id.okbutton_id);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeFragment();
}
}
);
return fragmentView;
}
private void closeFragment() {
getActivity().getFragmentManager().beginTransaction().remove(this);
}
}
EDIT:
code for MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment myFragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, myFragment, "myfragment");
fragmentTransaction.commit();
fragmentTransaction.remove(myFragment);
}
I tried to remove the fragment in the MainActiviy and there it WORKS. And more - I can put the reference in remove() which I cannot in the Fragment class
Use this
getActivity().getFragmentManager().popBackStack();
(or) use can specify tags
Example reference
You can pop the fragment by name. While adding fragments to the back stack, just give them a name.
fragmentTransaction.addToBackStack("fragB");
fragmentTransaction.addToBackStack("fragC");
Then in Fragment_C, pop the back stack using the name ie.. fragB and include POP_BACK_STACK_INCLUSIVE
someButtonInC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack ("fragB", FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
});
I'm not at my main computer right now, so can't check...
But i think you need to call getSupportFragmentManager() rather than getFragmentManager().
EDIT
Now I'm back at my computer I can confirm it is what I said above. It also helps that you have posted your activity code.
In your MainActivity you call:
MyFragment myFragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
i.e. you call getSupportFragmentManager() which is correct, and why it works.
..but in your Fragment you call the standard getFragmentManager() as below:
getActivity().getFragmentManager().beginTransaction().remove(this);
and as the fragment extends a Support fragment, when you try and call this it can't be found. However, if you change the above line to this:
getActivity().getSupportFragmentManager().beginTransaction().remove(this);
this will no longer not be found and your code should run.

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!

android fragment call from custom dialog

i am calling fragment from custom dialog. but i cant call fragment.
my onClick calling function
public void text_noteClick(View v){
Fragment fragments = new Text_Note_Fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.layout.note_text, fragments);
transaction.addToBackStack(null);
Toast.makeText(getApplicationContext(),"text",Toast.LENGTH_SHORT).show();
}
Toast is works successfully.
Text_Note_Fragment class is
public class Text_Note_Fragment extends Fragment {
public Text_Note_Fragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.note_text,container,false);
return view;
}
}
i think problem is Fragment replacing function.
sorry for my English :) TNX
I guess this line is the root cause.
transaction.replace(R.layout.note_text, fragments);
I see you use R.layout.note_text in onCreateView function, that's the layout xml for your fragment. but why you use it in replace function? you should use a container(often a FrameLayout), like this.
transaction.replace(R.id.container, fragments);

Go to previous fragment when press back button doesnt update FragmentAdapter

i have a activity A with fragment FA, from this fragment i go to FAB, this last fragment is a FragmentPagerAdapter.
When i go from A to FA to FB, press back button and return to FA, and go again to FB this fragment is not showing anything.
My getView method from pager adapter its not called.
This is my transactions code:
From A to FA:
private void setFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment replyGroupsFragment = new ReplyGroupsFragment();
Bundle bundle = new Bundle();
bundle.putString("title", reportName);
replyGroupsFragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, replyGroupsFragment, "ReplyGroupsFragment").commit();
getSupportActionBar().setTitle(getString(R.string.info));
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
From FA to FB (Use butterkniffe)
#OnItemClick(R.id.listViewReplyGroup)
void listClick(int position) {
List<DomainReplie> domainReplieArrayList = generateRepliesList(position);
setRepliesFragment((ArrayList<DomainReplie>) domainReplieArrayList);
}
And my PagerFragment contains this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReplyGroupsActivity replyGroupsActivity = (ReplyGroupsActivity) getActivity();
List<DomainReplie> replies = getArguments().getParcelableArrayList("replies");
adapter = new PagerAdapter(replyGroupsActivity.getSupportFragmentManager(), this, replies);
setActionBar();
}
#Override
public void onResume() {
super.onResume();
FirextApplication.getInstance().getBus().register(this);
}
#Override
public void onPause() {
super.onPause();
FirextApplication.getInstance().getBus().unregister(this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.work_containter_replies, container, false);
ButterKnife.inject(this, view);
pager.setAdapter(adapter);
return view;
}
Life cyrcle on both case are equals, but in second round screen doesnt show anything.
A little bit late, but maybe it will help others.
I had the same problem. Finally I've solved it and I made the same mistake as you... Here is the line which is causing the problem:
fragmentManager.beginTransaction().replace(R.id.container, replyGroupsFragment, "ReplyGroupsFragment").commit();
You are calling replace(), but replace() just replaces current fragment - you have to call add() for adding another fragment to back stack - that's also what fixes ButterKnife to load/update views again.
Note: ButterKnife changes a lot! Use bind() instead of inject()

Calling method of Fragment has no effect

And first of all thank you anyway for your help.
This is a difficult question for me.
Please I have an activity that contains 5 Fragments; on user interaction the Fragments get swapped.
I am using the ACL.
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
stackArray =new ArrayList<Integer>();
favQ =new ArrayList<Stock>();
tablet=true;
mBound = false;
fragmentActivity = this;
setContentView(R.layout.splashmain);
splashfragment =new splashFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.splashview,splashfragment);
fragmentTransaction.commit();
/*
other stuff....
*/
fragmentlista = new listafragment();
fragmentfavourites= new favouritesFragment() ;
worstbest = new WorstBest();
searchfragment = new searchFragment();
/*
other stuff....
*/
lt = mService.ritira();
worst=mService.ritiraWorst();
best=mService.ritiraBest();
favQ.clear();
favQ.addAll(mService.ritiraFav());
fragmentlista.prendiLista(lt);
worstbest.prendiListaWorst(worst);
worstbest.prendiListaBest(best);
if(favQ.size()>0)fragmentfavourites.prendiLista(favQ);
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
splashfragment.enableAll();
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
// --->>>>HERE THE SAME METHOD enableAll() WORKS!!! <---
/*
other stuff....
*/
}
//Method invoked to setup the configuration of the screen is layoutSchermo(int conf)
public static void layoutSchermo(int conf){
//Check if it is a Tablet in Landscape mode or not
//if it finds v2 than we are on a LARGE screen, then we check ORIENTATIO
fragmentActivity.setContentView(R.layout.main);
View v2 =(View)fragmentActivity.findViewById(R.id.view2);
if(v2==null
&
fragmentActivity.getResources().getConfiguration().orientation==
Configuration.ORIENTATION_PORTRAIT)
tablet=false;
//Calls the screen configuration LIST
if(conf==LIST){
fragmentActivity.setContentView(R.layout.main);
FragmentManager fragmentManager = fragmentActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(splashfragment);
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
//Remove old Fragment splashfragment
//At this point I expect the fragment splashfragment is destroyed
//OR NOT???
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
if(!tablet){fragmentTransaction.replace(R.id.view1, fragmentlista);}
if(tablet){
fragmentTransaction.replace(R.id.view1, splashfragment);
fragmentTransaction.replace(R.id.view2,fragmentlista );
} fragmentTransaction.addToBackStack(null);
stack= fragmentTransaction.commit();
stackArray.add(stack);
//Brand new fragments added
// --->>>>HERE THE SAME METHOD enableAll() NOT WORKING!!! <---
// --->>>>HERE THE SAME METHOD enableAll() NOT WORKING!!! <---
splashfragment.enableAll();
}
------------
So basically what happens and where the problem is:
The problem is in the method
layoutSchermo(int conf)
In the method layoutSchermo(int conf),
I detach a Fragment (splashfragment) and reattach it (together with another one).
It is not clear to me if when I call
remove(splashfragment)
Actually the Fragment is destroyed or not?
Additionally, whenever the Fragment freshly added is a new one or the old one,
why the call to
splashfragment.enableAll();
Has no effect ?
I expect it to work either it is the new or old Fragment!
Please enlighten me!
Thanks
maurizio
----------
EDIT EDIT EDIT EDIT EDIT EDIT
Here is the code of the fragment (I do not think it helps much)
ublic class splashFragment extends Fragment {
public View v;
public Button buttonfav;
public Button buttonBW;
public Button buttonSe;
public Button buttonLi;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.splashnew, container, false);
RelativeLayout box1 = (RelativeLayout)v.findViewById(R.id.box1);
//box1.setBackgroundColor(Color.BLUE);
buttonfav=(Button)v.findViewById(R.id.heart);
buttonBW=(Button)v.findViewById(R.id.star);
buttonSe=(Button)v.findViewById(R.id.search);
buttonLi=(Button)v.findViewById(R.id.lista);
buttonfav.setBackgroundResource(R.drawable.hearth_gray_tansp);
buttonBW.setBackgroundResource(R.drawable.star_gray_trans);
buttonSe.setBackgroundResource(R.drawable.search_gray_transp);
buttonLi.setBackgroundResource(R.drawable.list_gray_trans);
buttonfav.setEnabled(false);
buttonBW.setEnabled(false);
buttonSe.setEnabled(false);
buttonLi.setEnabled(false);
buttonfav.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.FAVOURITES);
}});
buttonBW.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.BESTWORST);
}});
buttonSe.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.SEARCH);
}});
buttonLi.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Quotes.layoutSchermo(Quotes.LIST);
}});
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) { }
public void enableAll(){
buttonfav.setEnabled(true);
buttonfav.setBackgroundResource(R.drawable.hearth);
buttonBW.setEnabled(true);
buttonBW.setBackgroundResource(R.drawable.star);
buttonLi.setEnabled(true);
buttonLi.setBackgroundResource(R.drawable.list);
buttonSe.setEnabled(true);
buttonSe.setBackgroundResource(R.drawable.search);
}
}
When exactly fragments are destroyed can't be known with any certainty. All you know is that it's called after onStop() and before onDetach().
As for your splashFragment.enableAll(), you haven't showed us what that method is so how can we know why it isn't working... Also, you haven't showed us the more general context of this layoutSchermo method. I say this because I suspect you're doing this all wrong. You have a static method, referencing activities somehow...(not clear how that's happening), setting the contentview on that activity reference..the whole thing just sets off some red flags.
SplashFragment.enableAll is most likely something that needs to be called inside of that Fragment's onAttach or onResume, but again it's impossible to know without some explanation from you.
EDIT
Ok, so I think you're going about this incorrectly. What you are effectively trying to accomplish is to "configure" your Fragment in a certain way (depending on some state) when you display it again. The issue here is that you don't know exactly when the View hierarchy of a Fragment is inflated or when exactly it's attached to the Activity, etc. In other words, trying to call methods that affect the UI of your fragment simply on the basis of having a reference to the object of a Fragment is a mistake. You need to hook into the lifecycle of your Fragment and do things "the correct way."
Here's what I recommend: create a static constructor for your Fragment that makes it easy to create the properly configured Fragment that you want. Here's what that might look like:
public class SplashFragment extends Fragment {
public static SplashFragment newInstance(Bundle bundle) {
SplashFragment splashFragment = new SplashFragment()
splashFragment.setArguments(bundle);
return splashFragment;
}
// or alternatively
public static SplashFragment newInstance(int favResource, int bwResource, int liResource, int seResource,
boolean favEnabled, boolean bwEnabled, boolean liEnabled, boolean seEnabled) {
SplashFragment splashFragment = new SplashFragment()
Bundle bundle = new Bundle();
bundle.putInt("fav_res", favResource);
bundle.putInt("bw_res", bwResource);
bundle.putInt"li_res", liResource);
bundle.putInt("se_res", seResource);
bundle.putBoolean("fav_enabled", favEnabled);
//...And so on
splashFragment.setArguments(bundle);
return splashFragment;
}
//Then....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setup your view as normal...then
buttonFav.setBackgroundResource(getArguments().getInt("fave_res"));
//.....etc
}
}
Now if you really need to be able to manipulate a Fragment without creating a new instance, then the only way I can think to do this is to add the fragment with a tag, as in the
replace(int containerViewId, Fragment fragment, String tag)
and
add (Fragment fragment, String tag)
varieties.
Then, later you can try to ask the fragment manager to find those fragment for you, i.e.
SplashFragment splashFragment = (SplashFragment) getFragmentManager().findFragmentByTag("some tag here");
Check that it's not null and then call your method on it...

Categories

Resources