I am trying to pass data from an activity to a fragment. I have four tab. The data has been passed but not shown for the first time, when I swipe other three tabs and get back to the first tab then the data are shown. I call the JSON data parsing method in the onCreate method of the activity. Here I Provide my code.
This is the Main#Activity.java
package com.example.iqbal.privateuniversityinfo;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// https://api.myjson.com/bins/lb6b8
// new https://api.myjson.com/bins/1gzo6k
public class Main2Activity extends AppCompatActivity {
String name, fac_and_sub, tution_fees, admission_info, contact;
private String div;
private int pos;
private RequestQueue mqueue;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
div = getIntent().getStringExtra("div");
pos = Integer.parseInt(getIntent().getStringExtra("pos"));
bundle = new Bundle();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
jsonParse();
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(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_main2, 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);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.university_details, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FacultyAndSubject facultyAndSubject = new FacultyAndSubject();
facultyAndSubject.setArguments(bundle);
return facultyAndSubject;
case 1:
TutionFees tutionFees = new TutionFees();
return tutionFees;
case 2:
Admission_info admission_info = new Admission_info();
return admission_info;
case 3:
Contact contact = new Contact();
return contact;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
}
private void jsonParse() {
String url = "https://api.myjson.com/bins/1gzo6k";
mqueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
switch (div) {
case "ctg":
if (i == pos) {
name = jsonObject.getString("name");
fac_and_sub = jsonObject.getString("faculty_and_sub");
tution_fees = jsonObject.getString("tution_fees");
admission_info = jsonObject.getString("admission_info");
contact = jsonObject.getString("contact");
bundle.putString("name", name);
bundle.putString("fac", fac_and_sub);
bundle.putString("fees", tution_fees);
bundle.putString("info", admission_info);
bundle.putString("contact", contact);
}
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mqueue.add(jsonArrayRequest);
}
}
Here the FacultyAndSubject class
package com.example.iqbal.privateuniversityinfo;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.RequestQueue;
public class FacultyAndSubject extends Fragment {
Context context;
TextView tv;
String name, fac, fees, info, contact;
private Bundle bundle;
private RequestQueue mqueue;
String div;
int pos;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.faculty_and_subject, container, false);
tv = v.findViewById(R.id.tv);
if (getArguments() != null) {
name = getArguments().getString("name");
fac = getArguments().getString("fac");
fees = getArguments().getString("fees");
info = getArguments().getString("info");
contact = getArguments().getString("contact");
}
tv.setText(name + "\n" + " " + fac + "\n" + fees + "\n" + info + "\n" + contact);
return v;
}
}
Try adding the code inside the case 0 of your switch as same in your default case too.
Also as suggested by #babich try setting the adapter after getting the response.
May be you need to set your viewPager after you get the data?
Add log-message of finish to your onResponse end and add it to your onCreateView of FacultyAndSubject
Than check what calls earlier.
Do you know how to add Log-messages and how to use LogCat?
public class SectionsPagerAdapter extends FragmentPagerAdapter {
FacultyAndSubject facultyAndSubject;
TutionFees tutionFees;
Admission_info admission_info;
Contact contact;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if(facultyAndSubject == null) {
facultyAndSubject = new FacultyAndSubject();
facultyAndSubject.setArguments(bundle);
}
return facultyAndSubject;
case 1:
if(tutionFees == null) tutionFees = new TutionFees();
return tutionFees;
case 2:
if(admission_info == null) admission_info = new Admission_info();
return admission_info;
case 3:
if(contact == null) contact = new Contact();
return contact;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
}
The first:
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.faculty_and_subject, container, false);
tv = v.findViewById(R.id.tv);
if (getArguments() != null) {
this.name = getArguments().getString("name");
this.fac = getArguments().getString("fac");
this.fees = getArguments().getString("fees");
this.info = getArguments().getString("info");
this.contact = getArguments().getString("contact");
updateData();
} else showLoading();
tv.setText(name + "\n" + " " + fac + "\n" + fees + "\n" + info + "\n" + contact);
return v;
}
public void updateData(String name, String fac, String fees, String info, String contact) {
stopLoading();
this.name = name;
this.fac = fac;
this.fees = fees;
this.info = info;
this.contact = contact;
}
The second:
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
switch (div) {
case "ctg":
if (i == pos) {
name = jsonObject.getString("name");
fac_and_sub = jsonObject.getString("faculty_and_sub");
tution_fees = jsonObject.getString("tution_fees");
admission_info = jsonObject.getString("admission_info");
contact = jsonObject.getString("contact");
if(mSectionsPagerAdapter.facultyAndSubject != null) {
mSectionsPagerAdapter.facultyAndSubject.
updateDate(name, fac, fees, info, contact)
} else {
mSectionsPagerAdapter.facultyAndSubject = new FacultyAndSubject();
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("fac", fac_and_sub);
bundle.putString("fees", tution_fees);
bundle.putString("info", admission_info);
bundle.putString("contact", contact);
facultyAndSubject.setArguments(bundle);
}
}
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Related
I'm having a problem here
i have activity with tablayout viewpager get objects from database and pass them by bundle to the tabs fragment
the problem is bundle getting null in the tab fragment
here is the Activity
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class Categorys extends DrawerActivity implements TabLayout.OnTabSelectedListener {
String url,result;
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
ProgressDialog progress;
DBhelper db;
Bundle bundle;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorys);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setDisplayShowHomeEnabled(true);
set();
db = new DBhelper(Categorys.this);
db.open();
List<ProductObj> productslistfromDB = db.getAllProductsUp();
db.close();
ProductObj product = productslistfromDB.get(0);
String namee = product.getName();
String details = product.getDetails();
String category = product.getcategory();
String ownerr = product.getOwner();
String weight = product.getWeight();
String size = product.getSize();
String price = product.getPrice();
String imageurl = product.getimageurl();
String owner_address = product.getOwner_address();
String owner_phone = product.getOwner_phone();
String UID = product.getUID();
productpojo productpoj = new productpojo();
productpoj.setName(namee);
productpoj.setDetails(details);
productpoj.setcategory(category);
productpoj.setOwner(ownerr);
productpoj.setWeight(weight);
productpoj.setSize(size);
productpoj.setPrice(price);
productpoj.setimageurl(imageurl);
productpoj.setOwner_address(owner_address);
productpoj.setOwner_phone(owner_phone);
productpoj.setUID(UID);
ArrayList<productpojo> productlisttosend = new ArrayList<>();
productlisttosend.add(productpoj);
Tab1 fragmentGet1 = new Tab1();
Tab2 fragmentGet2 = new Tab2();
bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", productlisttosend);
fragmentGet1.setArguments(bundle);
fragmentGet2.setArguments(bundle);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_clothes));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_electrical));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_hammer));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_cars));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_interior_accesories));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_buid));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
}
#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) {
}
#Override
public void onBackPressed() {
}
}
and here is the first fragment Tab1
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.ArrayList;
/**
* Created by toshiba c660-12T on 16/08/2016.
*/
public class Tab1 extends Fragment {
GridView gv;
int[] clicknums;
ArrayList<productpojo> productarraylist = null;
Bundle bundle;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, container, false);
bundle=this.getArguments();
if (bundle != null) {
productarraylist = bundle.getParcelableArrayList("arraylist");
}
go();
return view;
}
public void go(){
productpojo propoj; = productarraylist.get(0);
String namee = propoj.getName();
String details = propoj.getDetails();
String category = propoj.getcategory();
String ownerr = propoj.getOwner();
String weight = propoj.getWeight();
String size = propoj.getSize();
String price = propoj.getPrice();
String imageurl = propoj.getimageurl();
String owner_address = propoj.getOwner_address();
String owner_phone = propoj.getOwner_phone();
String UID = propoj.getUID();
ProductObj product = new ProductObj();
product.setName(namee);
product.setDetails(details);
product.setcategory(category);
product.setOwner(ownerr);
product.setWeight(weight);
product.setSize(size);
product.setPrice(price);
product.setimageurl(imageurl);
product.setOwner_address(owner_address);
product.setOwner_phone(owner_phone);
product.setUID(UID);
final ArrayList<ProductObj> productlist = new ArrayList<>();
productlist.add(product);
gv = (GridView) getView().findViewById(R.id.grid);
clicknums = new int[productlist.size()];
gv.setAdapter(new CustomGrid(getActivity(), productlist));
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int clicknum;
clicknums[position] = clicknums[position] + 1;
clicknum = clicknums[position];
String image = productlist.get(position).imageurl;
String text = productlist.get(position).name;
String owenr = productlist.get(position).owner;
Intent intent = new Intent(getActivity(), Product.class);
intent.putExtra("numofclick", clicknum);
intent.putExtra("title", text);
intent.putExtra("owner", owenr);
intent.putExtra("image", image);
//Start details activity
startActivity(intent);
}
});
}
and here is the second fragment Tab2
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.ArrayList;
/**
* Created by toshiba c660-12T on 16/08/2016.
*/
public class Tab2 extends Fragment {
GridView gv;
int[] clicknums;
ArrayList<productpojo> productarraylist = null;
Bundle bundle;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2, container, false);
bundle=this.getArguments();
if (bundle != null) {
productarraylist = bundle.getParcelableArrayList("arraylist");
}
go();
return view;
}
public void go(){
productpojo propoj; = productarraylist.get(0);
String namee = propoj.getName();
String details = propoj.getDetails();
String category = propoj.getcategory();
String ownerr = propoj.getOwner();
String weight = propoj.getWeight();
String size = propoj.getSize();
String price = propoj.getPrice();
String imageurl = propoj.getimageurl();
String owner_address = propoj.getOwner_address();
String owner_phone = propoj.getOwner_phone();
String UID = propoj.getUID();
ProductObj product = new ProductObj();
product.setName(namee);
product.setDetails(details);
product.setcategory(category);
product.setOwner(ownerr);
product.setWeight(weight);
product.setSize(size);
product.setPrice(price);
product.setimageurl(imageurl);
product.setOwner_address(owner_address);
product.setOwner_phone(owner_phone);
product.setUID(UID);
final ArrayList<ProductObj> productlist = new ArrayList<>();
productlist.add(product);
gv = (GridView) getView().findViewById(R.id.grid);
clicknums = new int[productlist.size()];
gv.setAdapter(new CustomGrid(getActivity(), productlist));
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int clicknum;
clicknums[position] = clicknums[position] + 1;
clicknum = clicknums[position];
String image = productlist.get(position).imageurl;
String text = productlist.get(position).name;
String owenr = productlist.get(position).owner;
Intent intent = new Intent(getActivity(), Product.class);
intent.putExtra("numofclick", clicknum);
intent.putExtra("title", text);
intent.putExtra("owner", owenr);
intent.putExtra("image", image);
//Start details activity
startActivity(intent);
}
});
}
pager class
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by toshiba c660-12T on 16/08/2016.
*/
//Extending FragmentStatePagerAdapter
public class Pager extends FragmentStatePagerAdapter {
//integer to count number of tabs
int tabCount;
//Constructor to the class
public Pager(FragmentManager fm, int tabCount) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
//Returning the current tabs
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
default:
return null;
}
}
//Overriden method getCount to get the number of tabs
#Override
public int getCount() {
return tabCount;
}
}
Need to call getArguments() in onCreateView to get Bundle which is send using setArguments :
bundle=this.getArguments();
how to switch between Fragment A and Fragment B in android TabLayout.
how to switch to next Fragment when Fargment Button Onclick is called.
Please help me
package com.digi.global.globalhub.fragment.offer;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.digi.global.globalhub.R;
import com.digi.global.globalhub.Utility.M;
import com.digi.global.globalhub.listener.FilterListener;
import com.digi.global.globalhub.listener.FragmentMove;
import com.digi.global.globalhub.listener.OfferFilter;
public class OfferFragmentActivity extends Fragment implements View.OnClickListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
PagerAdapter adapter;
ViewPager viewPager;
TabLayout tabLayout;
Context context;
Toolbar toolbar;
ImageView bizMenu;
PopupMenu popup;
public static OfferFragmentActivity mInstance = null;
public OfferFragmentActivity() {
// Required empty public constructor
}
public static OfferFragmentActivity newInstance(String param1, String param2) {
OfferFragmentActivity fragment = new OfferFragmentActivity();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
context = this.getContext();
mInstance = this;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view =inflater.inflate(R.layout.fragment_offer, container, false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
adapter = new PagerAdapter(getChildFragmentManager(), getContext());
tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
bizMenu = (ImageView) view.findViewById(R.id.bizMenu);
bizMenu.setVisibility(View.VISIBLE);
bizMenu.setOnClickListener(this);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.biz_ic, android.R.style.Theme_DeviceDefault));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.mipmap.ic_menu_white_36dp);
upArrow.setColorFilter(Color.parseColor("#B68426"), PorterDuff.Mode.SRC_ATOP);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(upArrow);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getString(R.string.Offers));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(final TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onClick(View v) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Fragment fragment = (Fragment) adapter.instantiateItem(viewPager, viewPager.getCurrentItem());
if(fragment instanceof OfferFilter){
switch (item.getItemId()) {
case R.id.bizTravel:
((OfferFilter) fragment).onFilterBizTravel("bizTravel");
return true;
case R.id.bizAssistance:
((OfferFilter) fragment).onFilterAssistance("bizAssistance");
return true;
case R.id.bizSolution:
((OfferFilter) fragment).onFilterSolution("bizSolution");
return true;
case R.id.partners:
((OfferFilter) fragment).onFilterPartner("partners");
return true;
case R.id.favoutites:
((OfferFilter) fragment).onFilterFavouritesBiz("favoutites");
return true;
}
return false;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentStatePagerAdapter {
String tabTitles[] = getResources().getStringArray(R.array.offerTab);
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
/* FragmentMove fragmentChanges = (FragmentMove) adapter.instantiateItem(viewPager, 2);
if(fragmentChanges instanceof FragmentMove) {
((FragmentMove) fragmentChanges).fragmentChanges();
}*/
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTWO();
case 2:
return new FragmentThree();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
/* public View getTabView(int position) {
View tab = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_layout, null);
TextView tv = (TextView) tab.findViewById(R.id.tabText);
tv.setText(tabTitles[position]);
return tab;
}*/
}
}
You can have a FragmentPagerAdapter to manager fragments and set this adapter into viewPager to slide fragments when you click on tabs or swipe to change tabs.
FragmentPagerAdapter:
public class TabLayoutViewPagerAdapter extends FragmentPagerAdapter {
private final int PAGE_COUNT = 3;
private final String[] mTabsTitle = {"Fragment A", "Fragment B, "Fragment C"};
private Context context;
private int[] mTabsIcons = {
R.drawable.a,
R.drawable.b,
R.drawable.c};
public TabLayoutViewPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
public View getTabView(int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
TextView title = (TextView) view.findViewById(R.id.title);
title.setText(mTabsTitle[position]);
title.setSingleLine(true);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setImageResource(mTabsIcons[position]);
return view;
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
return new FragmentA();
case 1:
return new FragmentB();
case 2:
return new FragmentC();
}
return null;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return mTabsTitle[position];
}}
How you use it:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
TabLayoutViewPagerAdapter pagerAdapter = new TabLayoutViewPagerAdapter(getSupportFragmentManager(), this);
if (viewPager != null) {
viewPager.setAdapter(pagerAdapter);
}
You need a TabLayout:
mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
if (mTabLayout != null) {
mTabLayout.setupWithViewPager(viewPager);
//populate your tabs
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab != null)
tab.setCustomView(pagerAdapter.getTabView(i));
}
TabLayout.Tab tab = mTabLayout.getTabAt(0);
if (tab != null && tab.getCustomView() != null) {
tab.getCustomView().setSelected(true);
}
}
How to select a page:
private void selectPage(int pageIndex) {
mTabLayout.setScrollPosition(pageIndex, 0f, true);
viewPager.setCurrentItem(pageIndex);
}
Do not forget to create your customTab.xml.
Best regards.
In Fragment A's onClick() method, try this :
TabActivity tabs = (TabActivity) getParent();
tabs.getTabHost().setCurrentTab(2);
I want to add gridview layout inside the tab layout of my current project is there any way I can add it or maybe inflate it with my current code?
This is my current mainactivity.java:
package id.WKKR.ktcafe;
import tabs.SlidingTabLayout;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
#
SuppressWarnings("deprecation")
public class MenuUtama extends ActionBarActivity {
GridView myGridView;
Toolbar toolbar;
private ViewPager mPager;
private SlidingTabLayout mTabs;#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_utama);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
NavDrawerFragment drawerFragment = (NavDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
mPager = (ViewPager) findViewById(R.id.MyPager);
mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mTabs = (SlidingTabLayout) findViewById(R.id.MyTabs);
mTabs.setDistributeEvenly(true);
mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabsText);
mTabs.setBackgroundColor(getResources().getColor(R.color.orange));
mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.brown));
mTabs.setViewPager(mPager);
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_utama, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(this, "This Is " + item.getTitle() + " Button", Toast.LENGTH_SHORT).show();
return true;
}
if (id == R.id.bill) {
startActivity(new Intent(this, BillTagihanAnda.class));
}
if (id == R.id.pesanan) {
startActivity(new Intent(this, DaftarPesananAnda.class));
}
if (id == R.id.callwaiter) {
startActivity(new Intent(this, PanggilPelayan.class));
finish();
}
return super.onOptionsItemSelected(item);
}
class MyPagerAdapter extends FragmentPagerAdapter {
int icon[] = {
R.drawable.ic_food, R.drawable.ic_drink, R.drawable.ic_desserts
};
String[] tabsText = getResources().getStringArray(R.array.tabs);
public MyPagerAdapter(FragmentManager fm) {
super(fm);
tabsText = getResources().getStringArray(R.array.tabs);
}
#
Override
public Fragment getItem(int position) {
MyFragment myFragment = MyFragment.getInstance(position);
return myFragment;
}
#
Override
public CharSequence getPageTitle(int position) {
Drawable drawable = getResources().getDrawable(icon[position]);
drawable.setBounds(0, 0, 40, 40);
ImageSpan imageSpan = new ImageSpan(drawable);
SpannableString spannableString = new SpannableString(" ");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
#
Override
public int getCount() {
return 3;
}
}
public static class MyFragment extends Fragment {
private TextView textView;
public static MyFragment getInstance(int position) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("position", position);
myFragment.setArguments(args);
return myFragment;
}
#
Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.my_fragment, container, false);
textView = (TextView) layout.findViewById(R.id.position);
Bundle bundle = getArguments();
if (bundle != null) {
textView.setText("The Page Selected is " + bundle.getInt("position"));
}
return layout;
}
}
}
and this is how the tab layout look like, it inflate the textview that showing the current position from array
http://i59.tinypic.com/9jopyc.jpg[/IMG]
thanks for anyone who want to help.
so i already add the gridview, now i was trying to inflate the gridview with image and textview, i'm using an adapter which look like this, but honestly i don't know how to make it works :
public static class MyFragment extends Fragment {
private TextView textView;
private GridView myGridView;
public static MyFragment getInstance(int position) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("position", position);
myFragment.setArguments(args);
return myFragment;
}
#
Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.my_fragment, container, false);
textView = (TextView) layout.findViewById(R.id.position);
myGridView = (GridView) layout.findViewById(R.id.gridView);
Bundle bundle = getArguments();
if (bundle != null) {
textView.setText("The Page Selected is " + bundle.getInt("position"));
}
return layout;
}
}
class Menus {
int imageId = 0;
String menus = "";
String menusPrices = "";
Menus(int imageId, String menus, String menusPrices) {
this.imageId = imageId;
this.menus = menus;
this.menusPrices = menusPrices;
}
}
//the adapter which inflate the gridview content
class MyCafe extends BaseAdapter {
ArrayList < Menus > list;
Context context;
MyCafe(Context context) {
this.context = context;
list = new ArrayList < Menus > ();
Resources res = context.getResources();
String[] tempMenusNames = res.getStringArray(R.array.food);
String[] tempMenusPrices = res.getStringArray(R.array.foodprices);
int[] menusImages = {
R.drawable.makanana, R.drawable.makananb,
R.drawable.makananc, R.drawable.makanand,
R.drawable.makanane, R.drawable.makananf
};
for (int i = 0; i < 6; i++) {
Menus tempMenus = new Menus(menusImages[i], tempMenusNames[i],
tempMenusPrices[i]);
list.add(tempMenus);
}
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int i) {
// TODO Auto-generated method stub
return list.get(i);
}
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
class ViewHolder {
ImageView myMenus;
TextView myMenusText;
TextView MyMenusPrice;
ViewHolder(View v) {
myMenus = (ImageView) v.findViewById(R.id.imageView1);
myMenusText = (TextView) v.findViewById(R.id.textView1);
MyMenusPrice = (TextView) v.findViewById(R.id.textView2);
}
}
public View getView(int i, View view, ViewGroup viewGroup) {
// TODO Auto-generated method stub
View row = view;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.single_item, viewGroup, false);
holder = new ViewHolder(row);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Menus temp = list.get(i);
holder.myMenus.setImageResource(temp.imageId);
holder.myMenusText.setText(temp.menus);
holder.MyMenusPrice.setText(temp.menusPrices);
return row;
}
}
Create grid view inside R.layout.my_fragment and inflate in fragment.
You can also use multiple fragment in your pager adapter.
In my app I want to use swipe views of four tabs inside a fragment. The four tabs are contains different fragments each and all the four fragments are sliding by swipe from right to left or vice versa. The fragments are working fine but the tabs are not visible within the fragment. Anyone have any solution for this. Thanks in advance :)
this is the main fragment which contains the tabs:-
public class DashboardTabFragment extends Fragment implements ActionBar.TabListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
private ViewPager viewPager;
public DashboardTabFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
setHasOptionsMenu(true);
ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
assert actionBar != null;
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
TabPageAdapter tabPageAdapter = new TabPageAdapter(getActivity().getSupportFragmentManager(), getActivity());
viewPager.setAdapter(tabPageAdapter);
for (String aTabTitle : tabTitle)
actionBar.addTab(actionBar.newTab().setText(aTabTitle).setTabListener(this));
return rootView;
}
This is the adapter for fragments:-
public class TabPageAdapter extends FragmentPagerAdapter {
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
I found the solution. I used TabHost for tabs with viewpager.
This is my fragment :-
package com.itpp.trt;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
public class DashboardTabFragment extends Fragment implements ViewPager.OnPageChangeListener {
private static final String ARG_SECTION_NUMBER = "arg_section_number";
private ViewPager mViewPager;
private TabHost tabHost;
private String[] tabSpec = {"Tab_1", "Tab_2", "Tab_3", "Tab_4"};
private String[] tabTitle = {"Cleanness", "Product Display", "Hygiene", "Asm Visits"};
private TabHost.TabContentFactory mFactory = new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
View v = new View(getActivity());
v.setMinimumHeight(0);
return v;
}
};
public static DashboardTabFragment newInstance(int position) {
DashboardTabFragment fragment = new DashboardTabFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position);
fragment.setArguments(args);
return fragment;
}
public DashboardTabFragment() {
tabHost = null;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dashboard_tab, container, false);
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
mViewPager.setAdapter(new TabPageAdapter(getChildFragmentManager(), getActivity()));
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
tabHost.setup();
mViewPager.setOnPageChangeListener(this);
for (int i = 0; i < tabSpec.length; i++) {
tabHost.addTab(tabHost.newTabSpec(tabSpec[i]).setIndicator(tabTitle[i]).setContent(mFactory));
}
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (tabId.equals("Tab_1")) {
mViewPager.setCurrentItem(0);
} else if (tabId.equals("Tab_2")) {
mViewPager.setCurrentItem(1);
} else if (tabId.equals("Tab_3")) {
mViewPager.setCurrentItem(2);
} else if (tabId.equals("Tab_4")) {
mViewPager.setCurrentItem(3);
}
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MyActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is my tabpager adapter :-
package com.itpp.trt;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by biswajit on 28-11-14.
*/
public class TabPageAdapter extends FragmentStatePagerAdapter{
Context context;
public TabPageAdapter(FragmentManager fm,Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CleannessChartFragment(context);
case 1:
return new ProductDisplayChartFragment(context);
case 2:
return new HygieneChartFragment(context);
case 3:
return new AsmVisitsChartFragment(context);
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
Hope this helps other. Thanks :)
Im having a problem here. i downloaded jake wharton. He gave an example of that which works great. But i want is from this i want to change that recent recent recent text to an activity.. so what i did is this , i put a class with .getname in there.. i thought it will be an activity but it convert it to text? this is the code of jake..
Test Fragment.java
package com.simple.viewpage;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public final class TestFragment extends Fragment {
private static final String KEY_CONTENT = "TestFragment:Content";
public static TestFragment newInstance(String content) {
TestFragment fragment = new TestFragment();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 20; i++) {
builder.append(content).append(" ");
}
builder.deleteCharAt(builder.length() - 1);
fragment.mContent = builder.toString();
return fragment;
}
private String mContent = "???";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView text = new TextView(getActivity());
text.setGravity(Gravity.CENTER);
text.setText(mContent);
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(text);
return layout;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_CONTENT, mContent);
}
}
Test FragmentAdapter.java
package com.simple.viewpage;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class TestFragmentAdapter extends FragmentPagerAdapter {
protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", };
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
and this is his main activity:
package com.viewpagerindicator.sample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.TabPageIndicator;
public class SampleTabsDefault extends BaseSampleActivity {
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
mAdapter = new GoogleMusicAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
class GoogleMusicAdapter extends TestFragmentAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length]);
}
#Override
public int getCount() {
return SampleTabsDefault.CONTENT.length;
}
#Override
public CharSequence getPageTitle(int position) {
return SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length].toUpperCase();
}
}
}
I change the Content String to this:
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres",ListTest.class.getName() };
Please help.. I want to view an activity and not convert it to text..
Please help.. I want to view an activity and not convert it to text..
You don't view an Activity, you view a Fragment. And you're not converting it, just retrieving its class name and using that as the label in the pager indicator.
I change the Content String to this:
Those are just the labels. The contents are different. The content is retrieved in:
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length]);
}
Jake put that code just an example.
It's up to you to switch(position) and return a new Fragment depending on the position you want to appear. I don't use that method (mine is slightly different), but how exactly you want to implement is up to you.
If you have other questions just ask. :-)
edited: a possible example:
static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
Fragment f;
switch(position) {
case 0:
f= new PlaceDataFragment();
break;
case 1:
f= new PlaceSelectorFragment();
break;
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
//DebugUtils.debugUI("getView(): " + f.toString());
return f;
}
}