How do I update a Fragment in a TabLayout with new data? - android

I am creating an application with 3 tabs. I have taken the code for a notepad-like app from here, and what I want is to put the notepad in a fragment inside a tab. I have done this but whenever I add a new note it is not reflected in the tab. I think I will have to use notifyDataSetChanged() but I am having difficulty as to where I can use it. Some help will be appreciated.
I have put a FAB in the tab. When I click it the app goes to the DisplayNote where I can enter the note title and content for the note as in the original app. I have confirmed that when I click "Save" the note is saved but the tab does not show this.
This is the relevant code for my MainActivity:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
}
This is the code for the Adapter:
class SectionsPagerAdapter extends FragmentStatePagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab 1";
case 1:
return "Tab 2";
case 2:
return "Notes";
default:
return null;
}
}
And this is the code for the third tab:
public class Tab3Notes extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mynotes, container, false);
FloatingActionButton add_note;
add_note = (FloatingActionButton) rootView.findViewById(R.id.add_note_button);
add_note.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getContext(), DisplayNote.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
return rootView;
}
}

Add this to your SectionsPagerAdapter:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Then when you call notifyDatasetChanged, the adapter will think all the pages are new and recreate them

Related

findFragmentById for a viewpager, of a tab, returns the same fragment regardless of the fragment displayed

I have a tab with two fragments. Regardless of the tab that is selected,
getSupportFragmentManager().findFragmentById(R.id.container)
returns the id of the fragment in the second tab every time.
I experimented and added another tab, repeating one of the fragments. Strange behaviour. Clicking the button on the first fragment changes the second, then clicking on the third changes the second and clicking the second changes the third. But then swiping between all the tabs resets only the first and third fragment.
Any idea how to fix or work around this?
Activity:
public class MainActivity extends AppCompatActivity {
//The {#link android.support.v4.view.PagerAdapter} that will provide fragments for each of the sections.
private SectionsPagerAdapter mSectionsPagerAdapter;
public android.support.v4.app.Fragment test;
//The {#link ViewPager} that will host the section contents.
private ViewPager mViewPager;
private ActivityMainBinding binding;
public interface Interface {
public void InterfaceMethod(int number);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Test button1 click behaviour
binding.button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Interface interfaceUse = (Interface)(getSupportFragmentManager().findFragmentById(R.id.container));
interfaceUse.InterfaceMethod(1);
}
});
}
protected void buttonClick(int a, int b){
int position = binding.tabs.getSelectedTabPosition();
}
//A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections/tabs/pages.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int index)
{
switch (index)
{
case 0:
return new UnitFragment();
case 1:
return new RmFragment();
case 2:
return new UnitFragment();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Unit Converter";
case 1:
return "One Rep Max";
case 2:
return "Dum";
}
return null;
}
}
}
UnitFragment:
public class UnitFragment extends Fragment implements MainActivity.Interface{
private TextView textview1;
public void InterfaceMethod(int position) {
textview1.setText(Integer.toString(position));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.unit_fragment, container, false);
//r.id
textview1 = (TextView) rootView.findViewById(R.id.textView);
return rootView;
}
}
Fix:
Interface interfaceUse =(Interface) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.container + ":" + mViewPager.getCurrentItem());
Try using this code in your button click,
binding.button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Interface interfaceUse = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.container + ":" + mViewPager.getCurrentItem());
interfaceUse.InterfaceMethod(1);
}
});

Orientation with Fragments, text is not saved

When I change the orientation of my mobile phone, the text content is not saved and the default text is put in the textview, in my android manifest in my activity Cafeteria I have this
android:configChanges="keyboardHidden|orientation"
Cafeteria
public class Cafeteria extends BaseActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cafeteria);
/*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);*/
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_cafeteria, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Oferta oferta = new Oferta();
return oferta;
case 1:
MenuCafe men = new MenuCafe();
return men;
case 2:
Carta carta = new Carta();
return carta;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.ofertas);
case 1:
return getString(R.string.menu);
case 2:
return getString(R.string.carta);
}
return null;
}
}
MenuCafe
public class MenuCafe extends Fragment{
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private AdaptadorMenu adapter;
private List<Menu> menu;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_menu);
menu = new ArrayList<>();
load_data_from_server(0);
linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new AdaptadorMenu(getContext(),menu);
recyclerView.setAdapter(adapter);
return rootView;
}
}
Thank you for the help
Try giving this in Android manifest file
android:screenOrientation="portrait"
You must save text content , because when rotation screen ,your activity will reset life cycle of android, same as first open.
See how to save the status here: Losing data when rotate screen

android studio change title using fragment

i have a problem with changing my title. i can change the title using fragment but each time i click or change to another fragment the title is didnt change to the correct title. here is my code:
This is my main tabactivity
public class TabActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_tab, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
profile_menu tab1 = new profile_menu();
return tab1;
case 1:
group_menu tab2 = new group_menu();
return tab2;
case 2:
world_menu tab3 = new world_menu();
return tab3;
case 3:
prize_menu tab4 = new prize_menu();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Profile ";
case 1:
return "Group ";
case 2:
return "World ";
case 3:
return "Prize";
}
return null;
}
}
public void setActionBarTitle(String title){
getSupportActionBar().setTitle(title);
}
}
and this is my fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.prize_menu, container, false);
getActivity().setTitle("Prize");
return rootView;
}
I assume that you want to change the title when tab change?
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
getSupportActionBar().setTitle("Profile ");
break;
case 1:
getSupportActionBar().setTitle("Group");
break;
case 2:
getSupportActionBar().setTitle("World");
break;
case 3:
getSupportActionBar().setTitle("Prize");
break;
default:
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().setTitle("YourTitle");
}
Use this line in onViewCreated() of each fragment will solve your problem
call getActivity().setTitle("Prize"); it in onResume of each fragment
In Fragment
Set your title in simple way. Add this method in your common class.
Add your title with back arrow in action bar.
public void setPageTitle(String title) {
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>"+title+ "</font>"));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstantState){
view = inflater.inflate(R.layout.fragment_name,container,false);
setPageTitle("title");
return view;
}
If you want title alone, use this line alone in your fragment onCreateView(). But this code does not handle back arrow.
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Title");
Quick way to do:
Declare your ToolBar as static and access from the fragment:
MainActivity:
public static Toolbar mToolbar;
in your fragment:
mToolbar.setTitle("your title here");
You set the Fragment title in the mobile_navigation.xml file in res -> navigation.
Use the android:label=""

How can a load to a specific tab / fragment in a Tablayout from a different activity using the Intent?

In activity A is a button. When you click the button in activity A it'll take you to TabbedActivity which has 5 tabs / fragments that show a list. Everytime I click on the button it will load to Tab1 by default. How can I make it load into Tab2 through the Onclick method? Grateful for any help. Try to leave detailed answers please, I'm new and get lost easily lol.
The onClick method in Activity A:
public void buttonInActivityA(View view) {
Intent intent = new Intent(getBaseContext(), TabbedActivity.class);
intent.putExtra("EXTRA_PAGE", 2);
startActivity(intent);
}
}
TabbedActivity which is a TabbedLayout:
public class TabbedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbed_activity);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("EXTRA_PAGE");
int position= Integer.parseInt(value );
ViewPager viewPager;
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setCurrentItem(2);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolTitle = (TextView) findViewById(R.id.toolbar_title);
toolTitle.setText(R.string.app_name);
toolTitle.setTextColor(Color.parseColor("#FFFFFF"));
setSupportActionBar(toolbar);
// add back arrow to toolbar_layout
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("PC HEALTH"));
tabLayout.addTab(tabLayout.newTab().setText("WIFI"));
tabLayout.addTab(tabLayout.newTab().setText("MISC"));
tabLayout.addTab(tabLayout.newTab().setText("HOW TO"));
tabLayout.addTab(tabLayout.newTab().setText("SHORT CUTS"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
This is the page adapter for the fragments:
class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentOne tab1 = new FragmentOne();
return tab1;
case 1:
FragmentTwo tab2 = new FragmentTwo();
return tab2;
case 2:
FragmentThree tab3 = new FragmentThree();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
FragmentTwo the frag and tab I need to load when clicked:
public class FragmentTwo extends Fragment {
public FragmentWifi() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_2, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// THIS IS HOW TO ADD LISTVIEWS INTO A FRAGMENT, FUCK YEAH!
ListView lv = (ListView)getActivity().findViewById(R.id.listView2);
String[] values = new String[] { "Example", "Example",
"Example", "Example" };
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, values);
lv.setAdapter(adapter);
// Handles items being clicked
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(getContext(), RandomActivity.class);
startActivity(intent);
}
}
}
);
}
}
First of all you can change default tab for TabActivity.
// set the default tab to the second tab
viewPager.setCurrentItem(1, false);
But it would be better to pass data to tabactivity and change it dynamically .
public class TheActivity extends TabActivity {
public static TheActivity self;
...
#Override
public void onCreate(Bundle savedInstanceState) {
self=this;
on any Activity running in a tab, when you want to change the one shown on your app. you can do this:
TabHost tabHost = TheActivity.self.getTabHost();
tabHost.setCurrentTab(0);

android : change tab and pager with button event in pager slidding tab strip

i use pager sliding tab strip in my app , i want to change tab and pager with button event how can i do that ?
i use this code but it`s not work
public class CheckoutMethod_Fragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
private Button btn_continue;
ViewPager pager;
public static CheckoutMethod_Fragment newInstance(int position) {
CheckoutMethod_Fragment f = new CheckoutMethod_Fragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.activity_checkout_method__fragment,
container, false);
final ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(new ViewPagerAdapter_PlaceCartOrder(getFragmentManager()));
btn_continue = (Button) v.findViewById(R.id.button_continue);
btn_continue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
//Replace right fragment with another fragment
pager.setCurrentItem(2);
}
});
return v;
}}
and this is ViewPagerAdapter_PlaceCartOrder
public class ViewPagerAdapter_PlaceCartOrder extends FragmentPagerAdapter {
private final String[] TITLES = { "Checkout Method","bbbb", "aaa ","ggg", "Order Review" };
public ViewPagerAdapter_PlaceCartOrder(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return CheckoutMethod_Fragment.newInstance(position);
case 1:
return CustomerInformation_Fragment.newInstance(position);
case 2:
return BillingInformation_Fragment.newInstance(position);
case 3:
return ShippingInformation_Fragment.newInstance(position);
case 4:
return ShippingMethod_Fragment.newInstance(position);
case 5:
return PaymentInformation_Fragment.newInstance(position);
case 6:
return OrderReview_Fragment.newInstance(position);
case 7:
return CheckoutMethod_Fragment.newInstance(position);
case 8:
return CheckoutMethod_Fragment.newInstance(position);
case 9:
return CheckoutMethod_Fragment.newInstance(position);
default:
return SuperAwesomeCardFragment.newInstance(6000);
}
// return SuperAwesomeCardFragment.newInstance(position);
}}
public class PlaceOrderActivity extends FragmentActivity {
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
Typeface typeface = Typeface.createFromAsset(getAssets(),
"fonts/Yekan.ttf");
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ViewPagerAdapter_PlaceCartOrder(getSupportFragmentManager()));
//pager.setCurrentItem(7);
// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setIndicatorColor(Color.rgb(225, 19, 18));
tabs.setIndicatorHeight(3);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.place_order, menu);
return true;
}
public void ChangeFragment(){
pager.setCurrentItem(2);
}}
There are 2 problems with your code:
The final View v in the onCreateView is shadowed by the View v being passed as an argument of the onClick method.
You need to setup pager before you can use it. At present, you are setting it up in the onClick method. You need to move the pager setup code to the onCreateView method.

Categories

Resources