Add fragment into viewPager's fragment - java

I have viewpager with 3 fragments (same layout - some EditText and Buttons) and I want to dynamically add small fragment above the viewpager fragment, write something in and then hide it.
This is what I tried:
MainActivity.java:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return MainFragment.newInstance("1");
case 1: return MainFragment.newInstance("2");
case 2: return MainFragment.newInstance("3");
default: return MainFragment.newInstance("");
}
}
#Override
public int getCount() {
return 3;
}
}
}
MainFragment.java:
public class MainFragment extends android.support.v4.app.Fragment {
EditText contentEdit;
String content, ID;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ID = getArguments().getString("msg");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
contentEdit = (EditText) view.findViewById(R.id.editText);
contentEdit.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
public void onSwipeBottom() {
final ViewGroup newView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.fragment_title, container, false);
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
container.removeView(newView);
}
});
container.addView(newView, 0);
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
return view;
}
}

Try to put a frame layout above that viewPager layout BUT set it's visibility to GONE therefore it won't "exist". Now in your pager onItemClick listener for that small fragment you want to show call findViewByID(R.id.YourFrameLayout).setVisibility(View.VISIBLE); and when you want to hide it, well you get the idea. Don't forget to add your fragment to that container, e.g. YourFrameLayout

Related

Tab Fragments not showing

I am trying to add tabs in a Fragment (for a bottom navigation bar). However, when I run the app, the tabs don't show up at all. Below is an image of the result:
IMAGE
Home.java -> the fragment that should display 2 tabs which includes BlankFragment.java
CategoryAdapater.java -> sets up the tab names and fragments to display in each tab
BlankFragment.java -> an empty fragment that is shown on each tab
How can I get it to work?
Home.java (the fragment that should show the tabs)
public class Home extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = rootView.findViewById(R.id.viewpager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
public Home() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
CategoryAdapater.java
public class CategoryAdapter extends FragmentPagerAdapter {
public CategoryAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new BlankFragment();
} else {
return new BlankFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Devices";
} else {
return "Numbers";
}
}
}
BlankFragment.java
public class BlankFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
return rootView;
}
public BlankFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
adapter addFragment missing
ViewPager viewPager = rootView.findViewById(R.id.viewpager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
BlankFragment frag= new BlankFragment ();
adapter.addFragment(frag);
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
public class Home extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
CategoryAdapter adapter = new CategoryAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
public Home() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Devices");
adapter.addFragment(new TwoFragment(), "Numbers");
viewPager.setAdapter(adapter);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Update Home Class with this code

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.

Where should I put my code when using a tabbed activity?

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/

How to change xml layout of second tab according to the selection of spinner item in first tab android

I have added 3 tabs as following.There is a spinner(drop down list) in “IntroductionFragment”.i want to change the layout of “RequirementFragment” programmatically according to the selection of spinner item in “IntroductionFragment”.Please help me
HomeLoanTabMainActivity.java
public class HomeLoanTabMainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Introduction", "Requirement", "Best offer" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_main_activity);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
TabsPagerAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new IntroductionFragment();
case 1:
return new RequirementFragment();
case 2:
return new BestOfferFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
IntroductionFragment.java
public class IntroductionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.introductionform_layout, container, false);
return rootView;
}
}
RequirementFragment.java
public class RequirementFragment extends Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.requirementFragment_layout, container, false);
return rootView;
}
}
Just give this a try
Inside your RequirementFragment.java add the onResume method as below:
public class RequirementFragment extends Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.requirementFragment_layout, container, false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
Toast.makeText(getActivity(), "Just check if you see this every time", Toast.LENGTH_SHORT).show();
}
}
Now run your code. In case you get the Toast every time you go back and forth then we can proceed.

Categories