Android Passing String from fragment to fragment - java

I have two fragments ListNav and SwipeNav in Navigation Drawer. ListNav shows list view of data from String array. SwipeNav shows data as swipe views of the same data from string array.
I am using single fragment for viewpager swipe views multiple tabs.
My problem is :
When I click on B in List View, it shows A in SwipeNav,
When I click on C in List View, it shows A in SwipeNav,
When I click on D in List View, it shows A in SwipeNav,
When I click on E in List View, it shows A in SwipeNav,
I want to get result:
If I click on B in List View, it will show B in SwipeNav,
If I click on C in List View, it will show C in SwipeNav,
If I click on D in List View, it will show D in SwipeNav
String Array:
<string-array name="tab_titles">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
<item>E</item>
<item>F</item>
<item>G</item>
<item>H</item>
<item>I</item>
........
</string-array>
I ListNav I use below to replace to SwipeNav with OnItemClickListener:
ListNav:
public class ListNav extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.nav_lis_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment12, new ListNavAdapter());
ft.commit();
ListNavAdapter:
public class ListNavAdapter extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nav_list_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tab_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
Bundle bundle = new Bundle();
bundle.putString("tab_titles", tabTitlesArray[i].toString());
SwipeNav fragobj = new SwipeNav();
fragobj.setArguments(bundle);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
}
In SwipeNav:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (getArguments() != null && !getArguments().isEmpty()) {
Bundle bundle = this.getArguments();
String myInt = bundle.getString("tab_titles");
}
return inflater.inflate(R.layout.nav_swipe, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
viewPager = (ViewPager) view.findViewById(R.id.pager);
viewPager.setAdapter(myPagerAdapter);
}
This is MyPagerAdapter:
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private String[] tabTitlesArray = null;
public MyPagerAdapter(FragmentManager fm, Context context) {
super(fm);
tabTitlesArray = context.getResources().getStringArray(R.array.tab_titles);
this.context= context;
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new AFragment();
Bundle args = new Bundle();
args.putString(AFragment.ARG_OBJECT, tabTitlesArray[i]);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return tabTitlesArray.length;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
Single fragment for tabbed activity AFragment:
public class AFragment extends Fragment {
public static final String ARG_OBJECT = "object";
public AFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(R.id.text1)).setText(args.getString(ARG_OBJECT));
return rootView;
}
nav_lis_layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment12"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
nav_list_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
I searched all answers in Stackoverflow. But fail to solve my problem why particular item click not showing same item to the next fragment.
I need your help plz.

you should not put into string commas
"tabTitlesArray[i]"
try with
""+tabTitlesArray[i]

When I click on B in List View, it shows A in SwipeNav,
The problem is because you are sending the same object but with different keys.
What you have to do is, in your onClick get the position of your adapter and put it to your bundle
bundle.putString("tab_titles", tabTitlesArray[i].toString());
Then you get the value using String myString = bundle.getString("tab_titles");
And then when you create the adapter, you can send the String via parameter and put the text in your adapter, anyways the code is a mess... It's very hard to understand.

In your SwipeNav, after you setup the ViewPager, you have not use viewPager.setCurrentItem() to change to your desired page. Since setCurrentItem() needs an integer argument, so the clicked position in the list needs to pass from ListNavAdapter to SwipeNav.
ListNavAdapter.java:
public class ListNavAdapter extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nav_list_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tab_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(), "Item: " + (i +1), Toast.LENGTH_SHORT).show();
String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
Bundle bundle = new Bundle();
bundle.putString("tab_titles", tabTitlesArray[i].toString());
bundle.putInt("tab_int", i); //Added
// set Fragmentclass Arguments
SwipeNav fragobj = new SwipeNav();
fragobj.setArguments(bundle);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
//Fragment f=getFragmentManager().findFragmentById(R.id.fragment12);
// if(f==null){
// getFragmentManager().beginTransaction().replace(((ViewGroup)(getView().getParent())).getId(), new SwipeNav()).commit();
// }
}
});
}
// Toast.makeText(getActivity(), "Item: " + (position +1), Toast.LENGTH_SHORT).show();
// Create new fragment and transaction
}
SwipeNav.java:
public class SwipeNav extends Fragment {
private MyPagerAdapter myPagerAdapter;
private ViewPager viewPager;
private int tab_int; //Added
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
//String passingString = getArguments().getString("TAG");
if (getArguments() != null && !getArguments().isEmpty()) {
Bundle bundle = this.getArguments();
String myInt = bundle.getString("tab_titles");
tab_int = bundle.getInt("tab_int"); //Added
return inflater.inflate(R.layout.nav_swipe, container, false);
} else {
return inflater.inflate(R.layout.nav_swipe, container, false);
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
viewPager = (ViewPager) view.findViewById(R.id.pager);
//viewPager.setId( R.id.pager );
viewPager.setAdapter(myPagerAdapter);
viewPager.setCurrentItem(tab_int); //Added
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Satyanusaran Bengali");
}
}
Hope that helps!

Related

ViewPager2 doesn't show Fragments

I am trying to implement ViewPager2 in my application and this is not the first time I am doing it but now it is not working.
I've been trying to find a solution for a couple of hours and trying different options but still - the fragments don't show up.
ViewPager2 is displaying correctly - I checked this by changing its background color.
I'm using the OneUI 2.4.0 library - but I've tested this library before and everything worked, and now it won't.
ViewPager2 Adapter
public class MainViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public MainViewPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new MainFragment();
case 1:
return new NewsFragment();
case 2:
return new ProfileFragment();
}
return null;
}
#Override
public int getItemCount() {
return 3;
}
}
MainFragment.java (other fragments code looks the same)
public class MainFragment extends Fragment {
View mRootView;
#Nullable
#Override
public View onCreateView(
#NonNull LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_main, container, true);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("MainFragment", "Initialized"); // I don't see that in logcat
}
}
fragment_main.xml (Other fragments have similar layout)
<?xml version="1.0" encoding="utf-8"?>
<de.dlyt.yanndroid.oneui.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.textview.MaterialTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/main_page"
android:textColor="#color/sesl_primary_text"
android:textSize="24sp"
android:textStyle="bold" />
</de.dlyt.yanndroid.oneui.widget.NestedScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ToolbarLayout mToolbarLayout;
private ViewPager2 mViewPager;
private TabLayout mTabLayout;
private MainViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
setup();
}
private void initialize() {
mToolbarLayout = (ToolbarLayout) findViewById(R.id.mToolbarLayout);
mViewPager = (ViewPager2) findViewById(R.id.mMainPager);
mTabLayout = (TabLayout) findViewById(R.id.mMainTabLayout);
}
private void setup() {
viewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), getLifecycle());
mViewPager.setAdapter(viewPagerAdapter);
}
And the problem is just that i don't see my fragments in ViewPager2.
try to
return mRootView
instead of
return super.onCreateView(inflater, container, savedInstanceState);
The place where you went wrong was when you did not add the layout to the root. The problem is this:
return super.onCreateView(inflater, container, savedInstanceState);
but, you r not using your view right? You are using the default view which is just empty. So, to solve it, you need to pass it your view instead of that. So, return your view like this:
return mRootView;

How to pass data from Fragment to Tablayout fragment

This is will run fragment in fragment that use viewpageAdapter.I want to pass data from fragment to tablayout fragment. i have try any method and still crash. i just want to passs once data to fragment in the tablayout.
First fragment. this line i want pass to tablayout fragment:-
specItem = getArguments().getString("spec_item");
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageUrl = getArguments().getString("image_url");
priceItem = getArguments().getString("price_item");
specItem = getArguments().getString("spec_item");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_details_item, container, false);
textPrice = (TextView) rootView.findViewById(R.id.textPrice);
image_Details = (ImageView) rootView.findViewById(R.id.image_Detail);
tabLayout = (TabLayout) rootView.findViewById(R.id.tablayout_id);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpage_id);
textPrice.setText(priceItem);
Picasso.get().load(imageUrl).into(image_Details);
ViewPageAdapter adapter = new ViewPageAdapter(getActivity().getSupportFragmentManager());
adapter.AddFragment(new FragmentSpecifications(), "Specification");
adapter.AddFragment(new FragmentReview(), "Review");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
Second fragment in tablayout, i dont know how to recieve:-
View rootView;
TextView textSpec;
String specItem;
public FragmentSpecifications() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_specification, container, false);
textSpec = (TextView) rootView.findViewById(R.id.textviewspec);
textSpec.setText();
return rootView;
}
Inside your FragmentSpecifications create a instance of the Fragment to send data to it, like this:
public static FragmentSpecifications newInstance(String priceItem) {
Bundle args = new Bundle();
args.putString("priceItem", priceItem);
FragmentSpecifications fragment = new FragmentSpecifications();
fragment.setArguments(args);
return fragment;
}
After that in same FragmentSpecifications override onCreate method and get value:
private String priceItem;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
priceItem = getArguments().getString("priceItem");
}
And finally when you add FragmentSpecifications do adapter pass the value:
adapter.AddFragment(FragmentSpecifications.newInstance(priceItem), "Specification");

Fragment Bundle

Please Help me!
What I'm doing wrong?
in Fragment1
#Override
public static Fragment1 newInstance(String param) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString("key","value");
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString("key");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
textview.setText(mParam1)
return v
in Activity onCreate
Fragment1.newInstance("text");
and in the end i have null in mParam1
Why?
I don't believe your mParam1 is null. I think your textview is null because you haven't referenced it. You need to give it a reference to the textview in the layout.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
TextView textview = v.findViewById(R.id.textview);
textview.setText(mParam1);
return v;
}
Also, you need to change args.putString("key", "value") to args.putString("key", param) if you expect to get the string you passed to the new instance and not get "value" set to all your textviews.
Also, make sure you import android.support.v4.app.Fragment; and add this to your MainActivity's onCreate:
Fragment fragment = Fragment1.newInstance("Text");
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, fragment, null)
.commit();
Where R.id.fragmentContainer is the id of your FrameLayout in your activity_main.xml.
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
If you don't have this, your onCreate in your fragment will never get called and will never inflate. I can't think of anything else it can be because your fragment code is fine. So the problem is in your main Activity.
You have to put the args to the Fragment from the parent Activity.
For instance if you use a ViewPager, in the adapter do the following when instantiating :
public class ParentActivity extends FragmentActivity {
private class MyAdapter extends FragmentStatePagerAdapter {
MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
fragment.setArguments(args);
switch (position) {
case 0:
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString("key", "MyString");
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 1;
}
}
}

Getting a String to another activity

(i want to make an app to show 40 articles of a news website.) I have a problem with getting a String to another class. I have a String "link" in my "Menu1.java" and want to use it in the "Menu1_1_Artikel.java".
The Getter Method is working. But i dont know how to set the value of "link".. Every time i try it it only gets "null" instead of the link of the article which is clicked on the listview. :/
public class Menu1 extends Fragment {
private ListView lv; //Listview which shows 40 articles from a news website
private ArrayAdapter adapter;
public ArrayList liste = new ArrayList();
private ProgressDialog progressDialog;
private String[] myStringArray = new String[40]; //Array with 40 URLs
public String link;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_1, container, false);
lv = (ListView)view.findViewById(R.id.list);
adapter = new ArrayAdapter(getActivity(), R.layout.list_item, liste);
new datenAbrufen().execute(); //Method which loads the 40 articles
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
link = myStringArray[position]; //Save the URL to the article which is clicked on the listview to "link"
Menu1 obj = new Menu1();
obj.setLink(link); //I think here is the problem because the value is not in the Getter Method..
Toast.makeText(getActivity(), link, Toast.LENGTH_LONG).show(); //Output: Shows the URL from article -> "link" have a value
//Fragment
Fragment fragment = null;
fragment = new Menu1_1_Artikel();
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
});
return view;
}
public String getLink(){
return this.link; //Problem: String "link" = null
}
public void setLink(String Str){
this.link= Str;
//Toast.makeText(getActivity(), link, Toast.LENGTH_LONG).show(); //Toast would show an Error: "Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference"
}
//[......]
}
public class Menu1_1_Artikel extends Fragment {
private String link;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
link= "Test";
Toast.makeText(getActivity(), "1.: "+link, Toast.LENGTH_LONG).show(); //Output: "Test"
Menu1 obj = new Menu1();
link= obj.getLink();
Toast.makeText(getActivity(), "2.: "+link, Toast.LENGTH_LONG).show(); //Output: "null"
return view;
}
//[......]
}
First you have to make the "Menu1" class to implement parcelable or serialisable,
Then, set the arguments to fragments,
Bundle bundle = new Bundle();
bundle.putParcelable("obj", obj);
Fragment fragment = null;
fragment = new Menu1_1_Artikel();
fragment.setArguments(bundle);
Then, retrieve it in another fragment like this as follows,
Menu1 latitude = getArguments().getParcelable("obj")
You should use bundle and extras:
Fragment fragment = null;
fragment = new Menu1_1_Artikel();
if (fragment != null) {
Bundle args = new Bundle();
args.putString("link", link);
fragment.setArguments(args);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
And receive the link ok Menu1_1_Artikel
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
Bundle bundle=getArguments();
link = bundle.getString("link");
Toast.makeText(getActivity(), "2.: "+link, Toast.LENGTH_LONG).show(); //Output: "null"
return view;
}

Passing data from listview in fragment to fragment

when i click on the listview the bundle can get the value, but cant pass the value to second fragment.
First Fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
}
});
return view;
}
Second Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
test = (TextView)view.findViewById(R.id.textView);
Bundle args = getArguments();
if (args != null && args.containsKey("category")){
String userId = args.getString("category");
test.setText(userId);
}
return view;
}
You may be forget to start your second fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.yourContainer, ldf);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
and in you second activity
Bundle agrs = getArguments();
if (args != null) {
String category = agrs.getString("category");
test.setText(category);
}
In First Fragment
categorylist.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String category = ((TextView) view.findViewById(R.id.mainproductitem)).getText().toString();
MainActivity main=new MainActivity();
main.openSecondFrag();
}
});
return view;
}
In your MainActivity,put openSecondFrag() method
public void openSecondFrag(){
details_fragment ldf = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category);
ldf.setArguments(args);
}
In Second Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
test = (TextView)view.findViewById(R.id.textView);
Bundle args = getArguments();
if (args != null && args.containsKey("category")){
String userId = args.getString("category");
test.setText(userId);
}
return view;
}
I am sure it will work.
HomeActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.activity.HomeActivity"
tools:showIn="#layout/app_bar_home">
//View that will hold all the fragments
<FrameLayout
android:id="#+id/container_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
FirstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment1, container, false);
view.setBackgroundColor(Color.WHITE);
listViewAdapter.SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
SecondFragment secondFrag = new SecondFragment();
Bundle args = new Bundle();
args.putString("Key","some value");
secondFrag .setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(R.id.container_view, fragment)
.addToBackStack(null)
.commit();
}
});
return view;
}
SecondFragment
public class SecondFragment extends Fragment {
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.second_fragment, container, false);
TextView textView = (TextView)view.findViewById(R.id.textView);
view.setBackgroundColor(Color.WHITE);
String key = getArguments().getString("Key");
//Set the value to your text view
textView.setText(key);
return view;
}
I tried this out and it works perfectly.
Try this: on your receiving Fragment:
Bundle agrs = this.getArguments();
if (args != null) {
String myStr = args.getString(key, defaultValue);
}
`Use this code in your categorylist.setOnItemClickListener`
// Create fragment and give it an argument specifying the article it should show
details_fragment newFragment = new details_fragment ();
Bundle args = new Bundle();
args.putString("category", category)
//Note: if your are in fragment than replace getSupportFragmentManager to getFragmentManager.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Use a Bundle. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(key, value);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container_view, bundle).commit();
Bundle has put methods for lots of data types. See this
Then in your Fragment, retrieve the data (e.g. in onCreate() method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getString(key, defaultValue);
}

Categories

Resources