I'm using this repo to create sliding tabs in an Android app:
https://github.com/ogaclejapan/SmartTabLayout
I used the demo code and reduced it to my needs and now I want to have only one Fragment class that handles all activities that should use sliding tabs. So I have the activity Cards and Walkthrough in my particular app I want to use sliding tabs.
The code of Cards is this:
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;
public class Cards extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
Demo demo = Demo.valueOf(String.valueOf(Demo.CARDS));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(demo.titleResId);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ViewGroup tab = (ViewGroup) findViewById(R.id.tab);
tab.addView(LayoutInflater.from(this).inflate(demo.layoutResId, tab, false));
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpagertab);
demo.setup(viewPagerTab);
FragmentPagerItems pages = new FragmentPagerItems(this);
for (int titleResId : demo.tabs()) {
pages.add(FragmentPagerItem.of(getString(titleResId), DemoFragment.class));
}
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(), pages);
viewPager.setAdapter(adapter);
viewPagerTab.setViewPager(viewPager);
}
public enum Demo {
CARDS(R.string.window_cards, R.layout.activity_slide);
public final int titleResId;
public final int layoutResId;
Demo(int titleResId, int layoutResId) {
this.titleResId = titleResId;
this.layoutResId = layoutResId;
}
public static int[] tabTitle() {
return new int[] {
R.string.title_cards1,
R.string.title_cards2,
R.string.title_cards3,
R.string.title_cards4,
R.string.title_cards5,
R.string.title_cards6
};
}
public void setup(final SmartTabLayout layout) { }
public int[] tabs() { return tabTitle(); }
}
}
And the other class is called DemoFragment:
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
public class DemoFragment extends Fragment {
private static final String TAG = "Cards";
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_demo, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int position = FragmentPagerItem.getPosition(getArguments());
WebView browser = (WebView) view.findViewById(R.id.webView);
browser.loadUrl("file:///android_asset/"+title+position+".html");
}
}
Now I just want to use this DemoFragment class this way that it will load the webview depending on the activity I'm in right now. But I don't know how to get the variable, like Cards in this example, just the current position of the tab with int position = FragmentPagerItem.getPosition(getArguments());.
I have not used this library, but it looks like you can supply your own arguments Bundle to the Fragments using on overloaded version of FragmentPagerItem.of().
for (int titleResId : demo.tabs()) {
Bundle args = new Bundle();
args.putString("page_source", ...);
pages.add(FragmentPagerItem.of(getString(titleResId), DemoFragment.class, args));
}
WebView browser = (WebView) view.findViewById(R.id.webView);
browser.loadUrl(getArguments().getString("page_source"));
Related
I have one app that have 2 tabs:
PESQUISA (Filter)
SEUS FAVORITOS (Your Favorite).
The "PESQUISA" tab: this tab has some card views.
The "SEUS FAVORITOS" tab: this tab has a listview.
Whenever I click in one card into "PESQUISA" tab I would like that add the information about card into listview, but I don't know how to update the listview in "SEUS FAVORITOS" tab.
Actually, the listview is updated when I close and open app again.
I tried search some examples in stack-overflow, google, but I cannot find.
MY ACTIVITY
public class FiltersActivity extends AppCompatActivity {
private CellPhone cellPhone;
private FavoriteFragment favoriteFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filters);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
List<String> titles = new ArrayList<>();
titles.add(getString(R.string.search));
titles.add(getString(R.string.your_favorite));
cellPhone = getIntent().getParcelableExtra("currentCellPhone");
final FiltersViewPagerAdapter mainViewPagerAdapter = new FiltersViewPagerAdapter(getSupportFragmentManager(), titles, cellPhone);
viewPager.setAdapter(mainViewPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
}
MY FAVORITE Fragment
public class FavoriteFragment extends Fragment {
private RecyclerView mRecycleView;
private CellPhoneFavoriteListAdapter mAdapter;
private List<CellPhone> cellPhoneList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
mRecycleView = (RecyclerView) view.findViewById(R.id.recycler_view_result_phones);
mRecycleView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecycleView.setLayoutManager(layoutManager);
DatabaseSQLiteService dao = new DatabaseSQLiteService(view.getContext());
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter = new CellPhoneFavoriteListAdapter(view.getContext(), cellPhoneList);
mRecycleView.setAdapter(mAdapter);
return view;
}
}
MY FragmentPagerAdapter
public class FiltersViewPagerAdapter extends FragmentPagerAdapter {
private List<String> mFragmentTitleList = new ArrayList<>();
private FragmentManager mFragmentManager;
private CellPhone cellPhone;
public FiltersViewPagerAdapter(FragmentManager fm, List<String> titles, CellPhone cellPhone) {
super(fm);
mFragmentManager = fm;
this.mFragmentTitleList = titles;
this.cellPhone = cellPhone;
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 0) {
fragment = new FiltersFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("currentCellPhone", cellPhone);
fragment.setArguments(bundle);
} else {
fragment = new FavoriteFragment();
Bundle bundle = new Bundle();
bundle.putInt("tipo", position);
fragment.setArguments(bundle);
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
My sugestion is to replace the List<String> titles, which is local to onCreate(), by a member variable List<TitleItem> which could be accessed by any of the fragments using a callback on the Activity. (The callback can be done by casting getActivity() to FiltersActivity in the Fragment, or by defining an interface and having FiltersActivity implement it.
On another side, TitleItem, would have the title String, and the state which would indicate if it is a favourite or not.
When a title is selected from PESQUIZA, it would the change the item's state (in the list). When the user switches to SEUS FAVORITOS, the lisview would be repopulated with items with favourite state active.
To repopulate the listview, as a ViewPager is in use, it would have to be done when the fragment becomes visible vs. the loading ahead of time that ViewPager does. To do this override public void setUserVisibleHint(boolean isVisibleToUser) and put the update logic in here.
EDIT I
I had wrongly interpreted the titles list as the list of items that could become favourites. After re-reading the question I see the items are being queried from the internal database.
What you cando is the following:
In the recycler view adapter add these methods:
public void setData(List<CellPhone> data) {
this.data = data;
refreshData();
}
private void refreshData(){
this.notifyDataSetChanged();
}
Note: data is the dataset member variable you defined probably with a different name.
Then in the fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Refresh your fragment here
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter.setData(cellPhoneList);
}
}
According to Juan help the correctly solution is:
In MY FAVORITE Fragment
public class FavoriteFragment extends Fragment {
private RecyclerView mRecycleView;
private CellPhoneFavoriteListAdapter mAdapter;
private List<CellPhone> cellPhoneList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
mRecycleView = (RecyclerView) view.findViewById(R.id.recycler_view_result_phones);
mRecycleView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecycleView.setLayoutManager(layoutManager);
DatabaseSQLiteService dao = new DatabaseSQLiteService(view.getContext());
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter = new CellPhoneFavoriteListAdapter(view.getContext(), cellPhoneList);
mRecycleView.setAdapter(mAdapter);
return view;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Update Listview here
DatabaseSQLiteService dao = new DatabaseSQLiteService(getContext());
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter.setData(cellPhoneList);
}
}
}
and in MY ADAPTER I just add two method
public void setData(List<CellPhone> data) {
this.itemsList = data;
refreshData();
}
private void refreshData(){
this.notifyDataSetChanged();
}
I am having a rather annoying problem using tabs in android. I am not sure how they work, problem I am having is knowing where to put the logic of my code. say for example on the first tab I wanted to apply a calendar and the second tab upload a file, for example where would I put this logic, I have 3 xml fragments and so far I have been trying to code the logic by the onCreateView. If anyone could explain how tabbed activities work I would be eternally grateful I used the default android set up for a tabbed activity and added 3 fragments.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_message, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2){
View rootView = inflater.inflate(R.layout.fragment_read, container, false);
TextView textView= (TextView)rootView.findViewById(R.id.textView_two);
textView.setText("Working");
return rootView;
}
else{
View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
// would I put my logic here?
return rootView;
}
}
}
Update 2
So now I am trying to listen for button presses and show a toast on one of the fragments,the button does not respond and the Toasts do not appear.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView=inflater.inflate(R.layout.fragment_calendar, container, false);
//final ActionBar actionBar = getSupportActionBar();
//actionBar.setDisplayHomeAsUpEnabled(false);
//actionBar.setTitle(null);
//Toast.makeText(getActivity(),"AKHBKH",Toast.LENGTH_LONG).show();
Button button1=(Button)rootView.findViewById(R.id.button_test1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("","");
Toast.makeText(getActivity(),"ddfdf",Toast.LENGTH_LONG).show();
}
});
PS I have tried all these on the Toast
getActivity()
getActivity().getApplicationContext()
getBaseContext()
getContext()
You can take three fragments and All the logic you want to implement should be in each of the fragment respectively. Take MainActivity to View all the fragments. Here i'll share my piece of code.
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Admin(), "ADMIN");
adapter.addFragment(new Faculty(), "FACULTY");
adapter.addFragment(new Student(), "STUDENT");
viewPager.setAdapter(adapter);
}
//----------------------------------------------------------------------------------------------
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed(){
//Do Here what ever you want do on back press;
}
}
I'll share the code of any one of the fragments: Admin
public class Admin extends Fragment {
EditText aid;
EditText apassword;
Button submit1,changepass;
String id = null, pass = null;
String table = null;
public Admin() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView=inflater.inflate(R.layout.fragment_admin, container, false);
aid=(EditText)rootView.findViewById(R.id.admin_id);
apassword=(EditText)rootView.findViewById(R.id.admin_password);
changepass=(Button)rootView.findViewById(R.id.changePass);
submit1=(Button)rootView.findViewById(R.id.submit1);
submit1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submit1();
}
});
changepass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in=new Intent(getActivity(),ChangePassword.class);
startActivity(in);
}
});
// Inflate the layout for this fragment
return rootView;
}
//For Admin login Authentication
public void submit1() {
id = aid.getText().toString();
pass = apassword.getText().toString();
Log.d("id", id);
Log.d("pass", pass);
table="admin";
// new ExecuteTask().execute(id, pass, table);
}}
Initially create an activity MainActivity.
You must create 3 fragments.Extend your activity from FragmentActivity and also implement ActionBar.TabListener
Refer this tutorial:
http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
I am using a ViewPager to show fragments. When i swipe it multiple times it gives following error:
E/libc++abi: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
--------- beginning of crash
A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 6900
I am showing and caching image (using this) as well as i am using TextView to show text on Fragment.
I tried to get help from other links but could not get succeed.
I tried to duplicate your issue on my side, however I'm not getting the error but the images are not loaded. But the files got cached in my internal storage. By the way, in your case, it is advisable to use Picasso or Universal Image Loader as those libraries will handle loading, caching and even error. This may not be your direct solution to your problem, but just in case if you're looking for alternative, you can try this solution.
For the sake of simplicity, I am using Picasso. I have created an example project just in case if you need reference. You need to add compile 'com.squareup.picasso:picasso:2.5.2' in your gradle dependency;
1) Fragment
public class FragmentImage extends Fragment {
private TextView imageName;
private ImageView image;
public static final String IMAGE_URL = "link";
public static final String POSITION = "position";
private String url = null;
private int position = 0;
public static FragmentImage newInstance(String link, int position) {
// Required empty public constructor
FragmentImage fragmentImage = new FragmentImage();
Bundle bundle = new Bundle();
bundle.putString(IMAGE_URL, link);
bundle.putInt(POSITION, position);
fragmentImage.setArguments(bundle);
return fragmentImage;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(null != getArguments()){
url = getArguments().getString(IMAGE_URL);
position = getArguments().getInt(POSITION);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_image, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
image = (ImageView)view.findViewById(R.id.image);
imageName = (TextView)view.findViewById(R.id.imageName);
imageName.setText("Position "+position);
Picasso.with(getActivity())
.load(url)
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(image);
}
}
2) FragmentAdapter
public class FragmentImagePager extends FragmentPagerAdapter {
private String[] imageUrls = {"https://www.ricoh.com/r_dc/caplio/r7/img/sample_04.jpg",
"http://i-cdn.phonearena.com/images/articles/47012-image/photo2.jpg",
"http://www.flooringvillage.co.uk/ekmps/shops/flooringvillage/images/request-a-sample--547-p.jpg",
"http://www.cameraegg.org/wp-content/uploads/2013/03/Canon-EOS-100D-Rebel-SL1-Sample-Image.jpg",
"http://imgsv.imaging.nikon.com/lineup/lens/singlefocal/wide/af-s_35mmf_14g/img/sample/sample4_l.jpg"};
public FragmentImagePager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FragmentImage.newInstance(imageUrls[position], position);
}
#Override
public int getCount() {
return imageUrls.length;
}
}
3) Activity
public class MainActivity extends AppCompatActivity{
private ViewPager fragmentList;
private FragmentImagePager fragmentImagePager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentList = (ViewPager)findViewById(R.id.fragmentList);
fragmentImagePager = new FragmentImagePager(getSupportFragmentManager());
fragmentList.setAdapter(fragmentImagePager);
fragmentList.setOffscreenPageLimit(fragmentImagePager.getCount());
}
}
I have been trying for 2 hours now to find the null pointer in my code and am having no luck. I am hoping one of you far smarter individuals than I can figure it out. First off, I am following the tutorial here: http://youtu.be/Y2liEQV3tbQ?list=PLonJJ3BVjZW4lMlpHgL7UNQSGMERcDzHo by slideNerd.
Here is what is baffling me: When in horizontal mode, the code executes perfectly and the displays are updated with correct information. This means that the horizontal portion of the if statement is working. When it is in portrait however and I click a list view icon, it immediately force closes with null pointer. The error comes from the line that reads:
f2b.changeTextView(index);
If I remove that line, the second activity opens without a problem. I am simply at a loss as to what has been causing me so much trouble.
Here are my classes:
MainActivity:
public class MainActivity extends Activity implements FragmentA.Communicator{
private FragmentA f1a;
private FragmentB f2b;
private FragmentManager manager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager=getFragmentManager();
f1a = (FragmentA) manager.findFragmentById(R.id.fragment1a);
f1a.setCommunicator(this); //the respond method that is implemented from Fragment a
f2b = (FragmentB) manager.findFragmentById(R.id.fragment2b);
}
#Override
public void respond(int index) {
//Check if portrait mode
if (f2b != null && f2b.isVisible()){ //Horizontal
f2b.changeTextView(index);
} else { //Vertical
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
Fragment A:
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener {
ListView listView;
Communicator comm;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.fragment_a_list_view);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.chapters, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
comm.respond(position);
}
public void setCommunicator(Communicator communicator){
this.comm = communicator;
}
//Interface to allow access between fragments
public interface Communicator{
public void respond(int index);
}
}
Fragment B:
public class FragmentB extends Fragment {
TextView textView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textView = (TextView) getActivity().findViewById(R.id.fragment_b_text_view);
}
public void changeTextView(int position){
String [] descriptions = getResources().getStringArray(R.array.descriptions);
textView.setText(descriptions[position]);
}
}
Activity2:
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
Intent intent = getIntent();
int index = intent.getIntExtra("index", 0);
//reference the fragment
FragmentB f2b = (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2b);
if (f2b != null){
f2b.changeTextView(index);
}
}
}
And Here is the error code in the logcat:
Caused by: java.lang.NullPointerException
at com.pgmacdesign.fragmentexamples3_flexibleui.FragmentB.changeTextView(FragmentB.java:42)
at com.pgmacdesign.fragmentexamples3_flexibleui.Activity2.onCreate(Activity2.java:25)
I have already confirmed that the index/ position variable is passing correctly. If anyone has any suggestions as to how to find the null pointer error, I would love the assistance.
In your Fragment B,
Try to replace textView = (TextView) getActivity().findViewById(R.id.fragment_b_text_view) by textView = (TextView) view.findViewById(R.id.fragment_b_text_view) and move it from onActivityCreated() to onCreateView().
Hope this helps.
I think your problem is when you can try to find the ID.
Try this textView = (TextView) view.findViewById(R.id.fragment_b_texT_view) where this view is your View view = inflater.inflate(R.layout.fragment_b, container, false);.
I've make it more simple and updated it based on the answers in my previous post: Adding Assigned Values in Spinner NullPointerException
I have a MainAcitivty that uses a ViewPager. I have 2 Fragments in my MainActivity (FragA and FragB)
In my FragA I have a spinner. While in FragB, I have a TextView and a Button.
Now what am I trying to do is, when I select "Hello" in my spinner, my int a will have a value of 5. And when I click the Button, 5 will display in the TextView.
Here's my code:
FragA
public class FragA extends Fragment {
Spinner spinner1;
String s1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fraga, container, false);
spinner1 = (Spinner) view.findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter_a = ArrayAdapter.createFromResource(getActivity(), R.array.spinner1,android.R.layout.simple_spinner_item );
spinner1.setAdapter(adapter_a);
s1 = spinner1.getSelectedItem().toString();
return view;
}
public int getInt() {
int a = 0;
if(s1.equals("Hello")) {
a = 5;
}
return a;
}
}
MainActivity
public class MainActivity extends FragmentActivity {
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
{
fragment = new FragA();
}
if (i == 1)
{
fragment = new FragB();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
public String get() {
FragA FragA = new FragA();
return Integer.toString(FragA.getInt());
}
}
FragB
public class FragB extends Fragment{
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragb, container, false);
textView = (TextView) view.findViewById(R.id.textview);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(Click);
return view;
}
OnClickListener Click = new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(((MainActivity)getActivity()).get());
}
};
}
By the way, I have no problem passing the value of a from FragA to FragB when this is my code:
public int getInt() {
int a = 5;
return a;
}
But, it doesn't involve my spinner and that's not I want to do.
Here is a simple way to communicate between fragments.
In MainActivity, keep static instances of the fragments.
public static FragA fragmentA;
public static FragB fragmentB;
Now if you want to access FragB from FragA, write something similar:
((MainActivity) getActivity()).fragmentB.setSomething();
And Here is a better/proper way to communicate between fragments:
http://developer.android.com/training/basics/fragments/communicating.html