How to verify the button pressed in a previous fragment - android

I apologize for my English ..
I am new to android development and am working with Fragments.
The doubt is as follows:
My first fragment has 2 buttons, button A and button B. Both lead for a second fragment with a list of items to be selected. Up to this point all right.
What I wonder is after selecting any item in the list must go to the third fragment then how to check if the A button was pressed to take the Fragment A or B button was pressed to take the Fragment B?

You must be calling the second fragment on Button click.
Do this inside onClick() method
Bundle bundle=new Bundle();
bundle.putString("selectedButton", "A"); // or B if button B is clicked
SecondFragment fragobj = new SecondFragment();
fragobj.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragobj).commit();
and to receive in second fragment's onCreateView() method like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String selectedButton = getArguments().getString("selectedButton"); // would give you A or B as passed
return inflater.inflate(R.layout.fragment, container, false);
}

When you create a Fragment you can pass it parameters.
For example:
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("someInt", someInt);
myFragment.setArguments(args);
return myFragment;
}
After that, in the onCreateView() you can receive them
getArguments().getInt("someInt", 0);
When you create the second fragment pass it a parameters that indicates if the "launcher" was button A or B

Related

passing data from parent Tab layout activity to fragment stops swapping of tabs

I have home activity which has 7 tabs. and for each tab I have created one fragment. Now I am transferring data from home fragment to other activity named Feature_Product_Activity which has 3 tabs, and here also for each tab I have created fragment. Then I am passing data from Feature_Product_Activity to one of the child fragment named FragmentFeatureOverview.
This is the method for passing data from Container Activity named Feature_Product_Activity to child Fragment named FragmentFeatureOverview
public void getValueFromFragment()
{
Bundle bundle = getIntent().getExtras();
getFeatureDescription= bundle.getString("desc");
Bundle b = new Bundle();
fragmentManager = getSupportFragmentManager();
b.putString("bb",getFeatureDescription);
FragmentFeatureOverview ff = new FragmentFeatureOverview();
ff.setArguments(b );
fragmentManager.beginTransaction().replace(R.id.fragmentContainer,ff).commit();
}
and in my fragment activity named FragmentFeatureOverview and getting data .
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_feature_overview, container, false);
TextView description = (TextView)view.findViewById(R.id.overview_Feature_description);
if(getArguments()!=null) {
String value = getArguments().getString("bb");
System.out.println("bundle is not null"+value);
description.setText(value);
}
return view;
}
I am getting the value in the bundle. But after setting the value in the TextView, Tabs Stops scrolling.
Any help will be greatly appreciated

Start an Activity which holds an Fragment, but need to press physical Back button twice to go back

I followed the document example (down in the page) created a list in a main Activity , when list item is selected I start an DetailActivity which adds a DetailFragment to container .
(I simplified the example code, I didn't implement the landscape mode thing, just simply start DetailActivity when a list row is selected.)
In MainActivity, when list item is clicked I do:
#Override
public void onItemSelected(int index) {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
My DetailActivity.java :
public static class DetailActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
//There is no layout xml for DetailActivity, we add the fragment programmatically to the activity.
FragmentManager fragManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragTransaction = fragManager.beginTransaction();
fragTransaction.add(android.R.id.content, details);
fragTransaction.addToBackStack(null);
fragTransaction.commit();
}
}
The DetailFragment.java :
public static class DetailsFragment extends Fragment {
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
}
I run my app, when I selecte a row, the DetailActivity is launched with the DetailFragment being shown on screen.
But I need to press physical Back button twice in order to go back the the list of MainActivity. Why I need to press twice back button?
I am testing on Android 4.4.4 device.
Because you're adding the fragment at runtime. The first press of the back button undoes the add of the fragment. The second finishes the activity. To prevent this, don't add the transaction where you first load the fragment to the back stack.

Determine fragment before current fragment

Imagine there is fragment A and fragment B.
if I click the button on fragment A, it leads to fragment C.
if I click the button on fragment B, it also leads to fragment C.
Now I want to detect from which fragment does the fragment C is created. Is it possible?
You can simply set a variable and pass that to Fragment C through bundle while doing FragmentTransaction like this as shown
Fragment fr=new FragmentA();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("from", "fragmentA");
fr.setArguments(args);
ft.replace(R.id.content_frame, fr);
ft.commit();
and you can retrieve the same in Fragment C like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("from"); // with value of strtext,you will get to know from which fragment you come from
return inflater.inflate(R.layout.fragment, container, false);
}
##You can pass a boolean value and toggle between two fragments.##
Bundle args = new Bundle();
args.putBoolean("key",true) // for fragement A
fr.setArguments(args);
ft.replace(R.id.content_frame, fr);
ft.commit();
if(getArguments().getBoolean("key");)
Log.e(LOGTAG,"FROM FRAGMENT A");
else
Log.e(LOGTAG,"FROM FRAGMENT B");

How do I use the same fragment for three tabs with different content?

I have an enum describing three different sports:
public enum MatchType {
S1(0, "Sport1", "xml stream address", R.id.match_list, R.layout.fragment_match_list, R.color.separator_sport1),
S2(0, "Sport2", "xml stream address", R.id.match_list, R.layout.fragment_match_list, R.color.separator_sport2),
S3(0, "Sport3", "xml stream address", R.id.match_list, R.layout.fragment_match_list, R.color.separator_sport3);
...getters/setters
}
I then have fragment with
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
matchesArrayAdapter = new MatchListAdapter(getActivity(), new ArrayList<Match>());
return inflater.inflate(matchType.getLayout(), container, false);
}
Also in my fragment I have an AsyncTask where I have this
#Override
protected void onPostExecute(final List<Match> matches) {
if (matches != null) {
matchListView = (ListView) getActivity().findViewById(matchType.getRId());
[setup listeners]
matchesArrayAdapter.matchArrayList = matches;
matchListView.setAdapter(matchesArrayAdapter);
}
}
EDIT:
In my Activity I have an AppSectionsPagerAdapter with
public Fragment getItem(int i) {
MatchListSectionFragment fragment = new MatchListSectionFragment();
Bundle bundle = new Bundle();
bundle.putInt(Constants.MATCH_TYPE, i);
fragment.setArguments(bundle);
return fragment;
}
EDIT 2:
Here's my onCreate and onCreateView from my fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
matchType = MatchType.getMatchType(bundle.getInt(Constants.MATCH_TYPE));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
matchesArrayAdapter = new MatchListAdapter(getActivity(), new ArrayList<Match>());
return inflater.inflate(matchType.getLayout(), container, false);
}
The AsyncTask reads an xml stream for each of the sports in my enum but my problem is that tab #1 is overwritten with data from tab #2 and subsequently tab #3.
Before I had a fragment defined for each sport but surely that can't be necessary?
How do I go about using the same fragment with the same layout for each sport?
When instantiating your fragment in your Activity set the Fragment's arguments with a Bundle.
Bundle myBundle = new Bundle();
myBundle.putInt(MY_EXTRA, 1);
myFragment.setArguments(myBundle);
In your bundle put some Extra that will be read in the fragment's onCreate() callback.
int i = getArguments().getInt(MY_EXTRA);
I am on mobile.
Put three FrameLayouts in a LinearLayout, named frame1, frame2 and frame 3. This will be your main Activity's layout.
Then in the Activity's oncreate() method, call getFragmentManager().getFragmentTransaction().
Instantiate the three fragments and send them the data, preferably through a Bundle.
On the Fragment Transaction call the add() or replace() method for each fragment, the first parameter is the id of the respective FrameLayout, the second parameter is the fragment itself.
Call commit().
You should create the newInstance method in your fragment, also you should store MatchType instansce in you fragment.
MatchType matchType;
public static MyFragment newInstance(MatchType matchType) {
MyFragment fragment = new MyFragment();
fragment.matchType = matchType;
return fragment;
}
In your Activity you should to create 3 instances of MyFragment with this method (with related to each fragment it owns MatchType). Then in onCreateView method you should insert data to your views from matchType.
Sorry, I'm on mobile. And sorry for my English.
Update
Check your variable matchType. Maybe it declared as static?

How to use setArguments() and getArguments() methods in Fragments?

I have 2 fragments: (1)Frag1 (2)Frag2.
Frag1
bundl = new Bundle();
bundl.putStringArrayList("elist", eList);
Frag2 dv = new Frag2();
dv.setArguments(bundl);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.the_fragg,dv);
ft.show(getFragmentManager().findFragmentById(R.id.the_fragg));
ft.addToBackStack(null);
ft.commit();
How do I get this data in Frag2?
Just call getArguments() in your Frag2's onCreateView() method:
public class Frag2 extends Fragment {
public View onCreateView(LayoutInflater inflater,
ViewGroup containerObject,
Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//here is your list array
String[] myStrings=bundle.getStringArray("elist");
}
}
EDIT:
Best practice is read and save arguments in onCreate method. It's worse to do it in onCreateView because onCreateView will be called each time when fragment creates view (for example each time when fragment pops from backstack)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
}
Eg: Add data:-
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
bundle.putString("board_id", board_id);
MapFragment mapFragment = new MapFragment();
mapFragment.setArguments(bundle);
Eg: Get data :-
String latitude = getArguments().getString("latitude")
You have a method called getArguments() that belongs to Fragment class.
in Frag1:
Bundle b = new Bundle();
b.putStringArray("arrayname that use to retrive in frag2",StringArrayObject);
Frag2.setArguments(b);
in Frag2:
Bundle b = getArguments();
String[] stringArray = b.getStringArray("arrayname that passed in frag1");
It's that simple.
Instantiating the Fragment the correct way!
getArguments() setArguments() methods seem very useful when it comes
to instantiating a Fragment using a static method.
ie Myfragment.createInstance(String msg)
How to do it?
Fragment code
public MyFragment extends Fragment {
private String displayMsg;
private TextView text;
public static MyFragment createInstance(String displayMsg)
{
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.setString("KEY",displayMsg);
fragment.setArguments(args); //set
return fragment;
}
#Override
public void onCreate(Bundle bundle)
{
displayMsg = getArguments().getString("KEY"): // get
}
#Override
public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
View view = inflater.inflate(R.id.placeholder,parent,false);
text = (TextView)view.findViewById(R.id.myTextView);
text.setText(displayMsg) // show msg
returm view;
}
}
Let's say you want to pass a String while creating an Instance. This
is how you will do it.
MyFragment.createInstance("This String will be shown in textView");
Read More
1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments
for those like me who are looking to send objects other than primitives,
since you can't create a parameterized constructor in your fragment, just add a setter accessor in your fragment, this always works for me.
If you are using navigation components and navigation graph create a bundle like this
val bundle = bundleOf(KEY to VALUE) // or whatever you would like to create the bundle
then when navigating to the other fragment use this:
findNavController().navigate(
R.id.action_navigate_from_frag1_to_frag2,
bundle
)
and when you land the destination fragment u can access that bundle using
Bundle b = getArguments()// in Java
or
val b = arguments// in kotlin

Categories

Resources