Tabbed Activity Page Title not showing - java

This is what I was trying to do, The "Tab One" "Tab Two" as my Tabbed Page Title. Ignore the Toolbar
I created an app that uses tabbed activity, I used the preset tabbed activity in android studio and modified it to my use. But I'm having a problem in showing the tabbed title. I'm working only on 2 tabs for now but i'm planning to add more as I progress.
Here is the codes for my Tabbed Activity Class
public class StudLearnTab extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
String key;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbed_content);
// 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);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Bundle bundle = new Bundle();
bundle.putString("keys",key);
fragment_tabbed_content tab1 = new fragment_tabbed_content();
tab1.setArguments(bundle);
return tab1;
case 1:
fragment_tabbed_activity tab2 = new fragment_tabbed_activity();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Content";
case 1:
return "Try Yourself";
}
return null;
}
}
}
My Fragments only contains the constructor and createview but I'll included it here for reference. Both fragments are almost the same.
public class fragment_tabbed_activity extends Fragment {
public fragment_tabbed_activity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabbed_activity, container, false);
return rootView;
}
}

Related

when moving from one fragment to other the elements of the former staying on screen

so i got one main activity that has a Tablayout and a ViewPager to present diffrent fragments.
when i move between the fragments with my Tablayout everything works good, but if i use a button to open fragment, when going back to the former fragment (by pushing the cancel button) the elements of the fragment i left staying on the screen (as in the picture).
i tried to use a method viewPager.setCurrentItem(0); in the fragment to go back to the homepage from the fragment instade of ft.replace(R.id.fragment_edit_reminder, new Main_Activity_fragment()).commit(); but it didn't moved back to my home fragment (with the repalce it does go back but as i saied the elements.
this is my main:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tableLayout = findViewById(R.id.Tablayouting);
final ViewPager viewPager = findViewById(R.id.ViewPager);
PagerAdapter pagerAdapter = new
PagerAdapter(getSupportFragmentManager(),tableLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tableLayout.addOnTabSelectedListener(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 fragment:
public class edit_reminder_fragment extends Fragment implements View.OnClickListener {
private Button cancelButton;
public edit_reminder_fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment edit_reminder_fragment.
*/
public static edit_reminder_fragment newInstance() {
edit_reminder_fragment fragment = new edit_reminder_fragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void onClick(View view)//TODO: make a utility method for switching fragments on the main_activity_fragment(see note).
{
switch (view.getId()) {//recognizing what button was pushed
case R.id.ButtonCancelReminder:
//region
FragmentTransaction ft = getFragmentManager().beginTransaction();
Main_Activity_fragment maf = new Main_Activity_fragment();
ft.replace(R.id.fragment_edit_reminder, maf).commit();
break;
//endregion
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_reminder_fragment, container, false);
cancelButton = view.findViewById(R.id.ButtonCancelReminder);
cancelButton.setOnClickListener(this);
return view;
}
}
my pagerAdapted class:
public class PagerAdapter extends FragmentPagerAdapter {
//https://www.youtube.com/watch?v=HHd-Fa3DCng&ab_channel=MasterCoding
private int numOfTabs;
public PagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Main_Activity_fragment();
case 1:
return new key_words_fragment();
case 2:
return new groups_and_points_fragment();
case 3:
return new Fragment_Past_Reminders();
case 4:
return new edit_reminder_fragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
in the picture we see the home page fragment ,on it 3 buttons (cancel, save, Add a sub reminder) that stayed from a fragment that open when clicking on the ADD NEW REMINDER button (when clicking on cancel in the second fragment it's going back to the home page):
First, try the following as an adaper:
public class PagerAdapter extends
FragmentPagerAdapter {
private final ArrayList<Fragment> mFragments = new ArrayList<>();
private final ArrayList<String> mFragmentTitle = new ArrayList<>();
public PagerAdapter(FragmentManager mManager) {
super(mManager);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitle.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitle.get(position);
}
public Fragment getFragment(int position) {
if (position < mFragments.size() && position >= 0) {
return mFragments.get(position);
}
return null;
}
}
Then in your MainActivity's onCreate, initialize the following:
mTabs = (TabLayout) findViewById(R.id.tabs);
mPager = (ViewPager) findViewById(R.id.view_pager);
mMainAdapter = new PagerAdapter( getSupportFragmentManager() );
setupContents();
Then the private method setupContents() as follows:
mMainAdapter.addFragment(new FragmentOne(), getResources().getString(R.string.tab_albums));
mMainAdapter.addFragment(new FragmentTwo(), getResources().getString(R.string.tab_songs));
mMainAdapter.addFragment(new FragmentThree(), getResources().getString(R.string.tab_playlists));
// you can add as many fragments as you wish
//just follow the previous method #mMainAdapter.addFragment
mPager.setAdapter(mMainAdapter);
mTabs.setupWithViewPager(mPager);
To get the current fragment:
public Fragment getCurrentFragment() {
return mMainAdapter.getFragment(mPager.getCurrentItem());
}
To check if the current fragment is FragmentOne:
private boolean isFragmentOne() {
return getCurrentFragment() instanceof FragmentOne;
}

Trying to send the userid from the activity to the viewholder fragment

I have created an android app in which I have added an activity called profileview.java on which users can view there or other user's profile data. Profileview activity contains two fragments post and likes on which I have to show the post that is been posted by the user and the post liked by the user but not getting any idea how to send the userid from the profileview activity to the other two fragments.
profileviewactivity.class
public class profileviewActivity extends AppCompatActivity {
public String userid;
private ViewPager viewPager;
private TabLayout tabLayout;
private settingtabAdopter Tabadapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profileview);
viewPager = (ViewPager) findViewById(R.id.viewpager);
Tabadapter = new settingtabAdopter(getSupportFragmentManager());
viewPager.setAdapter(Tabadapter);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
userid = getIntent().getExtras().get("userid").toString();
}
}
settingadapter.java
public class settingtabAdopter extends FragmentPagerAdapter {
public settingtabAdopter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
posttimeline postfragment = new posttimeline();
return postfragment;
case 1:
like chatfragment = new like();
return chatfragment;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int i) {
switch (i){
case 0:
return "Posts";
case 1:
return "Likes";
default:
return null;
}
}
}
posttimeline.java
public class posttimeline extends Fragment {
View posttimelineview;
public posttimeline() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
posttimelineview = inflater.inflate(R.layout.fragment_posttimeline, container, false);
return posttimelineview;
}
}
like.java
public class like extends Fragment {
View Likeview;
public like() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Likeview = inflater.inflate(R.layout.fragment_like, container, false);
return Likeview;
}
}
i want to send userid from the profileaviewactivity to the posttimeline and like fragment.
pass userid as parameter at settingtabAdopter constructor
public settingtabAdopter(#NonNull FragmentManager fm, String userid)
profileviewActivity -> onCreate
Tabadapter = new settingtabAdopter(getSupportFragmentManager(), userid);
make private variable inside settingtabAdopter
private String userid;
initialize it inside constructor
this.userid = userid
Create private variable in each fragment and add setter (posttimeline and like) fragments
private String mUserid;
void setMUserId(String mUserid){
this.mUserid = mUserid;
}
On settingtabAdopter inside getItem function after initialize each fragment set the private varaible with the userid
public Fragment getItem(int position) {
switch (position){
case 0:
posttimeline postfragment = new posttimeline();
postfragment.setMUserId(userid)
return postfragment;
case 1:
like chatfragment = new like();
chatfragment.setMUserId(userid)
return chatfragment;
default:
return null;
}
}

OnClick Fragment to Fragment switch results in Blank Screen

When switching from one fragment to another fragment (within the second tab of my application), my second fragment is blank. I have tried the solutions linked here, but none seem to work:
Transaction of fragments in android results in blank screen
Android: Getting white screen with fragment transaction
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_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter, and add pages.
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter.addPage(new Received());
mSectionsPagerAdapter.addPage(new Send());
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_alert_partners, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_received, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2) {
View rootView = inflater.inflate(R.layout.fragment_send, container, false);
return rootView;
}
else {//main empty fragment in case of error. Never used in normal behaviour.
View rootView = inflater.inflate(R.layout.fragment_alert_partners, container, false);
return rootView;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//Create an Array list that will hold the pages.
ArrayList<Fragment> pages = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return pages.get(position);
}
//Add a page
public void addPage(Fragment f) {
pages.add(f);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Send";
}
return null;
}
}
}
SendFragment:
public class Send extends Fragment {
private OnFragmentInteractionListener mListener;
private TextView text1;
public Send() {
// Required empty public constructor
}
#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
View v = inflater.inflate(R.layout.fragment_send, container, false);
//Need getView() for fragment since setContentView must be set first but is not possible in fragment.
text1 = (TextView)v.findViewById(R.id.textview1);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Send2 send2 = new Send2();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.hide(Send.this);
fragmentTransaction.add(android.R.id.content, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return v;
}
public interface OnFragmentInteractionListener {
}
}
Send2Fragment:
public class Send2 extends Fragment {
private OnFragmentInteractionListener mListener;
public Send2() {
// Required empty public constructor
}
#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 v = inflater.inflate(R.layout.fragment_send2, container, false);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
}
}
Had to add a framelayout at the end of the layout code for the fragment I was replacing:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/send1frameLayoutId">
</FrameLayout>
Then used this code to switch to a fragment in the same tab of the previous fragment:
Fragment send2 = new Send2();
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.send1frameLayoutId, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

How To Hide View on Specific Fragment

I want to hide a GridView by setting drawerGrid.setVisibility(View.GONE); when the ViewPager is on a specific layout. Do I need to implement a onPageListener or is there an easier option?
Launcher.java
public class Launcher extends FragmentActivity {
DrawerAdapter drawerAdapterObject;
GridView drawerGrid;
class Package {
Drawable icon;
String name;
String label;
}
Package[] packs;
PackageManager pm;
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
drawerGrid = (GridView) findViewById(R.id.content);
pm=getPackageManager();
set_packs();
drawerAdapterObject = new DrawerAdapter(this, packs);
drawerGrid.setAdapter(drawerAdapterObject);
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
}
public void set_packs() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packsList = pm.queryIntentActivities(mainIntent, 0);
packs = new Package[packsList.size()];
for(int I=0;I<packsList.size();I++){
packs[I]= new Package();
packs[I].icon=packsList.get(I).loadIcon(pm);
packs[I].name=packsList.get(I).activityInfo.packageName;
packs[I].label=packsList.get(I).loadLabel(pm).toString();
}
}
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_apps,container,false);
}
}
Fragment2.java
public class Fragment2 extends Fragment {
ViewPager viewpager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_homescreen,container,false);
}
}
You can do that in two ways:
As you mentioned by using addOnPageChangedListener
Using callback when your fragment become visible to user
How to determine when Fragment becomes visible in ViewPager:
try this;
public class MyFragment extends Fragment {
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//hide view here
}
else {
}
}
}
setUserVisibleHint
Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore.
here isVisibleToUser boolean: returns true if this fragment's UI is currently visible to the user (default), false if it is not.

Passing Parameters from Activity to Another Activity Fragements

I have main activity that contains major parameters that I need to pass to all the application activities. (username - User Privilege - Team .. ETC).
I know how to do that except in an activity that contains three fragments, that are displayed using pager and tablayout. How can I pass the parameters to all these fragments? .. should I pass it to the activity then pass it to the three fragments as a second step? if yes, how can I pass to the fragments in the below code:
Second Activity Java:
public class DCODatabase extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dcodatabase);
Toolbar toolbar = (Toolbar) findViewById(R.id.DCODatabaseToolbar);
setSupportActionBar(toolbar);
assert toolbar != null;
toolbar.setLogo(R.drawable.dco1);
//Receving bundle from main activity// --> Working
Bundle extras = getIntent().getExtras();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab);
assert tabLayout != null;
tabLayout.addTab(tabLayout.newTab().setText("General Reports"));
tabLayout.addTab(tabLayout.newTab().setText("Report Display"));
tabLayout.addTab(tabLayout.newTab().setText("New Report"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount(),extras);
assert viewPager != null;
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) {
}
});
}
}
Pager Adapter:
public class PagerAdapter extends FragmentStatePagerAdapter{
int mNumOfTabs;
private final Bundle fragmentBundle;
public PagerAdapter(FragmentManager fm, int mNumOfTabs, Bundle bundle) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
this.fragmentBundle = bundle; ---> Receving in Adapter.
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
DCOGeneralReports tab1 = new DCOGeneralReports();
tab1.setArguments(fragmentBundle); --> Sending to fragement
return tab1;
case 1:
DCOReportDisplay tab2 = new DCOReportDisplay();
return tab2;
case 2:
DCO_New_Report tab3 = new DCO_New_Report();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Fragment Example:
public class DCOGeneralReports extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dco_general_report, container, false);
// here the problem. (SavedInstance is null! --> Not Receving the data)
Name = savedInstanceState.getString("Name");
UserGroup = savedInstanceState.getString("UserGroup");
Team = savedInstanceState.getString("Team");
Inside activity class when you create an instance of adapter you can pass the argument, so that you can retrieve that value in adapter's constructor.
Inside getItem() method of PagerAdapter try this
Bundle =new Bundle();
b.putString("key","value");
tab1.setArgument(b);
return tab1;
And also there is no need of passing argument for each activity till you need it in final activity.you can write it by using getIntent.putExtra() so that later it can be retrieved by using the getExtra("key")
In order to pass the value create an instance like this
ArrayList demo=new ArrayList();
demo.add("A");
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount(),demo);
And in adapter class change the constructor
ArrayList frag;
public PagerAdapter(FragmentManager fm, int mNumOfTabs,ArrayList frag) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
this.frag = frag;
}

Categories