hi,
it is my project in the photo. my project has custom listView in every page and listViews are filled with json data.
i writed every tab's onCreateView event Toast message to clarify problem and see what has happened.
for example, when i click 2.th tab, i get "2 worked" then "3 worked" as toast message. also add same data to listview over and over again btw.
sorry if i couldn't explain my problem.
here is my codes.
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new VasitaTurFragment();
.
.
.
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 6;
}
MainActivity:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "1", "2", "3","4","5","6" };
ModelFragment mF= new ModelFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
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) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Fragment:
public class MenseiFragment extends Fragment {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Mensei> menseiList = new ArrayList<Mensei>();
private ListView listView;
private menseiCLA adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.mensei, container, false);
listView = (ListView) rootView.findViewById(R.id.listView1);
adapter = new menseiCLA(getActivity(), menseiList);
listView.setAdapter(adapter);
Toast.makeText(getActivity(),"2 worked",
Toast.LENGTH_LONG).show();
JsonArrayRequest commonReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject objAna = response.getJSONObject(i);
Mensei mensei = new Mensei();
.
.
menseiList.add(mensei);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(commonReq);
return rootView;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}}
This is the default behavior of viewpager, so if you click on each tab the two neighbors of it automatically created and both run in onResume. if you really want they do something only when they are visible use below function for each tab fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisible()){
if(isVisibleToUser){
Log.d("MyTag","My Fragment is visible");
}else{
Log.d("MyTag","My Fragment is not visible");
}
}
}
Related
I am working on a app, which having a category list.
If we click on category then I have to show different subcategories in tabs, each tab having a list of products.
Everything is working fine tabs and fragment are loaded with correct data, only recyclerview onClick gives incorrect item(items from adjacent fragment's recyclerview). Mostly happens on viewpager swipe.
code in Activity:
PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount(), response);
// response is a list of subcategories and products
viewPager.setOffscreenPageLimit(1);
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) {
}
});
code in PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
SubCategoryResponse response;
public PagerAdapter(FragmentManager fm, int NumOfTabs, SubCategoryResponse response) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.response = response;
}
#Override
public Fragment getItem(int position) {
L.m(position +" => "+response.getList().get(position).getProducts().get(0).getName());
TabFragment fragmentDummy = TabFragment.getInstance(position, response.getList().get(position).getProducts());
return fragmentDummy;
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
code in TabFragment:
public class TabFragment extends Fragment implements ProductAdapter.mClickListener {
#Bind(R.id.list_container_fragment)
LinearLayout listContainerFragment;
#Bind(R.id.list_products)
RecyclerView productListView;
private ProductAdapter productsAdapter;
private Dialog myDialog;
private LinearLayoutManager linearLayoutManager;
private ArrayList<Products> responseProducts = null;
public TabFragment() {
// Required empty public constructor
}
public static TabFragment getInstance(int position, ArrayList<Products> response) {
TabFragment fragmentDummy = new TabFragment();
Bundle args = new Bundle();
args.putParcelableArrayList("PRODUCTS", response);
args.putInt("position", position);
fragmentDummy.setArguments(args);
return fragmentDummy;
}
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.responseProducts = args.getParcelableArrayList("PRODUCTS");
}
#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 view = inflater.inflate(R.layout.fragment_tab, container, false);
ButterKnife.bind(this, view);
linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
productListView.setLayoutManager(linearLayoutManager);
productListView.setItemAnimator(new DefaultItemAnimator());
populateList();
return view;
}
public void populateList() {
L.m("populate list");
if (responseProducts.size() > 0) {
L.m("Inside populate list => " + responseProducts.get(0).getName());
productsAdapter = new ProductAdapter(responseProducts);
productsAdapter.setListner(getActivity(), this);
productListView.setAdapter(productsAdapter);
productListView.setHasFixedSize(true);
} else {
showError("No Products to Show");
}
}
public void showError(String msg) {
SnackbarManager.show(
Snackbar.with(getActivity()) // context
.text(msg) // text to be displayed
.textColor(Color.WHITE) // change the text color
// .textTypeface(myTypeface) // change the text font
.color(getResources().getColor(R.color.colorPrimary)) // change the background color
.duration(Snackbar.SnackbarDuration.LENGTH_LONG)
, getActivity());
}
#Override
public void mClickDetails(View view, int pos) {
startActivity(new Intent(getActivity(), ProductDetailsActivity.class)
.putExtra("PRODUCT", responseProducts.get(pos).getName()));
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//populateList();
}
}
I don't know whats going wrong here.
Please help, Thank You.
Well fixed the problem,
Removed static field from RecyclerView Adapter.
Now working fine.
when i run this code,the toast in two different fragments are displayed on one tab. when i swipe to next tab nothing is displayed.
this is is my main tab activity:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Offers", "Distance", "Happy Hours","Shop List" };
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
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) {
}
}
this is adapter class :
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
Bundle bundle = new Bundle();
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
Fragment of = new OfferFragment();
bundle.putString("OfferFragment", "OfferFragment");
of.setArguments(bundle);
return of;
case 1:
Fragment df = new DistanceFragment();
bundle.putString("DistanceFragment", "DistanceFragment");
df.setArguments(bundle);
return df;
case 2:
Fragment hf = new HappyHoursFragment();
bundle.putString("HappyHoursFragment", "HappyHoursFragment");
hf.setArguments(bundle);
return hf;
case 3:
Fragment sf = new ShoplistFragment();
bundle.putString("ShoplistFragment", "ShoplistFragment");
sf.setArguments(bundle);
return sf;
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
this is my first fragment :
public class OfferFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// public static final String ARG_OBJECT = "object";
View rootView = inflater.inflate(R.layout.offerfragment, container,
false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.offer);
name = args.getString("OfferFragment");
txtview.setText(args.getString("OfferFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
this is my second fragment :
public class DistanceFragment extends Fragment {
private String name;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.distancefragment, container, false);
Bundle args = getArguments();
TextView txtview = (TextView) rootView.findViewById(R.id.distance);
name = args.getString("DistanceFragment");
txtview.setText(args.getString("DistanceFragment"));
display();
return rootView;
}
private void display() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
}
any suggestions are appreciated. am stuck with this.
This is because next fragment is created by pager
before showing toast check if that fragment is visible or not
if(fragmentName.this.isVisible())
{
// do your stuff here
}
Write onResume() in every fragment class.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Display Toast message here
}
}
I have an ActionBar that contains 11 tabs and 1 fragment. I also have a ViewPager to display the fragment(s). When a tab is clicked it creates the same fragment. The tabs display dates so they change everyday. What I need is to send the text of the tab (ie. .getTabText()) to the fragment, this will change the content of the fragment. I am having so much trouble trying to figure out how to do this. Here is all my code:
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private ArrayList<TopRatedFragment> myFragmentList = new ArrayList<TopRatedFragment>();
// Tab titles
String[] tabs = {this.getCurrentDate(-5).toString(),this.getCurrentDate(-4).toString(),this.getCurrentDate(-3).toString(), this.getCurrentDate(-2).toString(),this.getCurrentDate(-1).toString(),
this.getCurrentDate(0).toString(),
this.getCurrentDate(1).toString(), this.getCurrentDate(2).toString(), this.getCurrentDate(3).toString(), this.getCurrentDate(4).toString(), this.getCurrentDate(5).toString(),};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (String tab_name : tabs) {
TopRatedFragment fm = new TopRatedFragment();
fm.getTabs(tab_name);
myFragmentList.add(fm);
}
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), myFragmentList);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
actionBar.setSelectedNavigationItem(5);
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
public String getTab(Tab tab) {
return tab.getText().toString();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public String getCurrentDate(int offset) {
String calAsString;
DateFormat formatter = new SimpleDateFormat("MM/dd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, offset);
calAsString = formatter.format(cal.getTime());
return calAsString;
}
}
Here is my FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
ArrayList<TopRatedFragment> myList;
public TabsPagerAdapter(FragmentManager fm, ArrayList<TopRatedFragment> myList) {
super(fm);
this.myList = myList;
}
#Override
public Fragment getItem(int index) {
return myList.get(index);
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return myList.size();
}
And here is my simple fragment (for now):
public class TopRatedFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void getTabs(String tabs) {
Log.e("TRF", tabs);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
}
Create a static newInstance method to create fragment and bundle the args for the fragment. Pull the args in the fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (String tab_name : tabs) {
TopRatedFragment fm = new TopRatedFragment.newInstance(tab_name);
fm.getTabs(tab_name);
myFragmentList.add(fm);
}
public class TopRatedFragment extends Fragment {
public static Fragment newInstance(String position) {
TopRatedFragment f = new TopRatedFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("num", position);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle b = getArguments();
if (b!=null){
String someText = b.containsKey("num")?b.getString("num"):null;
}
Currently I have made 3 tabs. On each tab (fragment) there is a thread to fetch content and display it with a listview through an ArrayAdapter.
Now when you scroll through the tabs the thread gets executed again and again (not necessary).
Is there a way to stop this ? Or do I need to write the content to external storage for faster access ?
Also sometimes I see the same data on different tabs , how to avoid this ?
Thanks in advance
This is some code that I use inside my fragment which that is called multiple times when swiping :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
rootView = inflater.inflate(R.layout.leadlist, container, false);
profielen = new ArrayList<Profile>();
new getLeaderboards().execute(url);
lv = (ListView) rootView.findViewById(android.R.id.list);
lbadapter = new LeaderBoardAdapter(this.getActivity(), R.layout.item_layout, profielen);
return rootView;
}
public static class getLeaderboards extends AsyncTask<String, Void, JsonObject> {
#Override
protected JsonObject doInBackground(String... urls) {
JsonObject x = parseURL.GetJSON(urls[0]);
return x;
}
#Override
protected void onPostExecute(JsonObject obj) {
Gson gson = new Gson();
System.out.println(obj.toString());
JsonArray arr = obj.get("rows").getAsJsonArray();
for (int i=0;i<10;i++) {
Profile pat = gson.fromJson( arr.get(i) , Profile.class);
profielen.add(pat);
}
lv.setAdapter(lbadapter);
}
}
My FragmentActivity :
public class LeaderboardsActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Tab1", "Tab2", "Tab3" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.leaderboard);
Intent i = getIntent();
String region = i.getStringExtra("region");
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(),region);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
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) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
I would like to create a new fragment every time when I click its tab.
I tried to get the tab and to create a fragment. But it doesn't seem to work.
Here is my code.
Main Activity
public class MainActivity extends FragmentActivity {
private static ViewPager viewPager;
private static TabsPagerAdapter mAdapter;
private static ActionBar actionBar;
// Tab titles
private String[] tabs = { "TopRated", "Hots", "NEW"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(tabListener));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
static ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
};
TabsPagerAdapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new TopRatedFragment();
case 1:
return new HotStoryFragment();
case 2:
return new AllClassFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
One of the fragments
public class HotStoryFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Refresh_F","(2) HotStory");
View rootView = inflater.inflate(R.layout.fragment_hotstory, container, false);
TextView tvStudy = (TextView)rootView.findViewById(R.id.text);
return rootView;
}