I want to design the android application with slider(like website) when the user swipes from left to right or right to left I want to change the background not the whole view. I need a design like below. Please help me with native code samples
see this Library its may helps you
https://github.com/JakeWharton/Android-ViewPagerIndicator/
You can use View pager.
public class ImageDownloader extends Fragment {
public ImageDownloader() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.frag_image, null);
Bundle bundle = getArguments();
String imageUrl = bundle.getString("imageUrl");
ImageView mView2 = (ImageView) mView.findViewById(R.id.image);
ImageLoader mImageLoader = new ImageLoader(getActivity());
mImageLoader.DisplayImage(imageUrl, mView2);
return mView;
}
}
public class FragmentAdapter extends FragmentStatePagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return mdataStrings[position];
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("imageUrl", mdataStrings[position]);
ImageDownloader mDownloader = new ImageDownloader();
mDownloader.setArguments(bundle);
return mDownloader;
}
#Override
public int getCount() {
return mdataStrings.length;
}
}
And Use Like this :
mdataStrings = GlobalVars.stories.get(pos)
.getUpload_images().split(",");
mViewPager = (ViewPager) findViewById(R.id.viewpager);
FragmentAdapter titleAdapter = new FragmentAdapter(
getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
for (int i = 0; i < mdataStrings.length; i++) {
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.indicator);
ImageView mImageView = new ImageView(
StoriesDetails.this);
mImageView.setTag(i + "");
if (i == 0) {
mImageView
.setBackgroundResource(R.drawable.black_circle);
} else {
mImageView
.setBackgroundResource(R.drawable.white_circle);
}
mLinearLayout.addView(mImageView);
}
mViewPager
.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int page) {
// TODO Auto-generated method stub
System.out.println("Page : " + page);
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.indicator);
mLinearLayout.getChildAt(page)
.setBackgroundResource(
R.drawable.black_circle);
for (int i = 0; i < mdataStrings.length; i++) {
if (page != i) {
mLinearLayout
.getChildAt(i)
.setBackgroundResource(
R.drawable.white_circle);
}
}
}
#Override
public void onPageScrolled(int arg0,
float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int page) {
// TODO Auto-generated method stub
}
});
Related
I created an Tab based application using viewpager and Tablayout. When i click a button new tabs are created with a child fragment.
What I need is to assign different tab id to my tabs and each should be different. I tried i take the position of tabs but unfortunately, it doesn't work. when i tried to toast the position using below code it works only initially when the first tab is created and doesn't work for other tabs created. I don't know why this happens. ALso if i delete the tabs the position is not getting correct.
So I need an alternative solution to assign a TAB id (number or name) to each new tabs created so that when each tab is created I need to call a request to server with that id and populate data based on the tab ID
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
My ViewPageradapter is:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
int selectedTabPosition;
private boolean doNotifyDataSetChangedOnce = false;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
removeTab(position);
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
if (getCount() > 0) tabLayout.setupWithViewPager(viewPager);
//viewPager.setCurrentItem(getCount() - 1);
setupTabLayout();
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
ImageView tabItemAvatar =
(ImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
tabItemAvatar.setImageResource(R.drawable.boy);
return view;
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Parent Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS"+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void addPage(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
CHILD FRAGMENT :
public class FragmentChild extends Fragment {
String childname;
TextView textViewChildName;
EditText editText;
private GridView mGridView;
private ListItem mListItem;
private ListView mListview;
private ProgressBar mProgressBar;
private ProductViewAdapter mGridAdapter;
private ListViewAdapter mListAdapter = null;
private ArrayList<GridItem> mGridData;
private ArrayList<ListItem> mListData = null;
ListView listView;
CheckInterNetConnection check ;
Boolean isInternetPresent = false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
//textViewChildName = (TextView) view.findViewById(R.id.textViewChild);
//textViewChildName.setText(childname);
//editText = (EditText) view.findViewById(R.id.editText);
//editText.setText("");
}
private void setEvents() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("onActivityCreated","onActivityCreated");
mGridView = (GridView) getView().findViewById(R.id.gridView);
mGridData = new ArrayList<>();
mGridAdapter = new ProductViewAdapter(getActivity(), R.layout.grid_product_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
mListview = (ListView) getView().findViewById(R.id.list);
mListData = new ArrayList<>();
mListAdapter = new ListViewAdapter(getActivity(), R.layout.list_row, mListData);
mListview.setAdapter(mListAdapter);
}
#Override
public void onStart() {
super.onStart();
Log.e("onSTart","onSTart");
check = new CheckInterNetConnection(getActivity());
isInternetPresent = check.isConnectingToInternet();
if (isInternetPresent) {
//fetchProducts();
}
}
public void fetchProducts(){
Log.e("URL","http://13.126.17.194/products.php");
RestClientHelper.getInstance().get("http://13.126.17.194/products.php?tabid="{TAB ID HERE}, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
parseResult(response);
mListData.clear();
mListAdapter.setGridData(mListData);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
try {
ListItem items;
GridItem item = (GridItem) parent.getItemAtPosition(position);
items = new ListItem();
items.setName(item.getTitle());
items.setType(item.getDescription());
mListData.add(items);
}
catch(Exception e){
}
finally {
mListAdapter.setGridData(mListData);
}
}
});
}
#Override
public void onError(String error) {
}
});
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("products");
GridItem item;
if(posts.length() <= 0){
RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
ly.setVisibility(View.VISIBLE);
}
else {
// RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
//ly.setVisibility(View.INVISIBLE);
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String title = post.optString("name");
String description = post.optString("description");
String image = post.optString("image");
String qty = post.optString("qty");
String quantityin = post.optString("quantityin");
String price = post.optString("price");
item = new GridItem();
item.setId(id);
item.setTitle(title);
item.setDescription(description);
item.setImage(image);
item.setQuantity(qty);
item.setQuantityIn(quantityin);
item.setUnitprice(price);
mGridData.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
finally {
mGridAdapter.setGridData(mGridData);
}
}
}
PARENT FRAGMENT:
public class FragmentParent extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private ImageView add;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
getIDs(view);
setEvents();
return view;
}
private void getIDs(View view) {
viewPager = (ViewPager) view.findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) view.findViewById(R.id.my_tab_layout);
add= (ImageView) view.findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
viewPager.setAdapter(adapter);
}
int selectedTabPosition;
private void setEvents() {
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
viewPager.setCurrentItem(tab.getPosition());
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(getActivity(), "Selected " + tab.getPosition(), Toast.LENGTH_SHORT).show();
Log.d("Selected", "Selected " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
Log.d("Unselected", "Unselected " + tab.getPosition());
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(getActivity(), "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS"+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS"+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void addPage(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(adapter.getCount() - 1);
//setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
PLEASE HELP ME TO SOLVE THIS
Here is my solution for the question:
First, create an id file under res/values named ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="tab_id_one" type="id"/>
<item name="tab_id_two" type="id"/>
</resources>
Then, within the code where tabs are created, do the following:
for (int i = 0; i< tabLayout.getTabCount(); i++) {
TabLayout.Tab mTab = tabLayout.getTabAt(i);
if (mTab != null) {
switch (i){
case 0:
View tabViewOne = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tabViewOne.setId(R.id.tab_id_one);
//ect..
break;
case 1:
View tabViewTwo = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
tabViewTwo.setId(R.id.tab_id_two);
//ect..
break;
case 2:
//etc..
}
}
}
Note: Views tabViewOne and tabViewTwo can be made global variables where it will give access to their ids anywhere within the class/activity/fragment.
In your viewPager Adapter extends FragmentPagerAdapter this and include these methods and it will give new ID to every Fragment and when you add manually data in array and call notifyDataSetChange(), also call this method notifyChangeInPosition(mItems.size() - 1);.
From this the added item get a new ID.
private long baseId = 0;
ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return mItems.size();
}
//this is called when notifyDataSetChanged() is called
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public long getItemId(int position) {
// give an ID different from position when position has been changed
return baseId + position;
}
/**
* Notify that the position of a fragment has been changed.
* Create a new ID for each position to force recreation of the fragment
*
* #param n number of items which have been changed
*/
void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
You can use the setTag() method of TabLayout.Tab to use any Object you want as an identifier. You could do this in your setupTabLayout() method, where you are setting your custom view for each Tab.
For example, to use a String:
tabLayout.getTabAt(i).setTag("tab_" + i);
You can then later check the tag of each tab in your parent fragment with tab.getTag();
I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
I have to call a fragment (Page1) from here...
protected void onPostExecute(Void args) {
Intent intentx;
intentx = new Intent(HomeFragment.this.getActivity(),Main.class);
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentx);
}
I my program i have Main class which looks like this
public class Main extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Express(1 Day)", "Premium (2 Day)", "Normal (3+ Days)" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab);
// 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 class will invoke Page1,Page2,Page3
Inside Page 1 the code is this
public class Page1 extends Fragment {
public static ArrayList<String> strArr;
public static ArrayList<ArrayList<String>> content;
public static ArrayAdapter<String> adapter;
LinearLayout ll;
View format;
float days_to_del;
int[] no_of_count= new int[20];
int count;
int x;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.page1, container, false);
// super.onResume();
//View rootView = inflater.inflate(R.layout.page1, container, false);
for(int j=0;j<10;j++)
{
days_to_del=Float.parseFloat(""+Lib.result[j][0].toString());
if(days_to_del==2.0)
{
no_of_count[x]=j;
x++;
count++;
}
}
for(int m=0;m<count;m++)
{
ll = (LinearLayout) rootView.findViewById(R.id.parent);
LayoutInflater vi = (LayoutInflater) Page1.this.getActivity().getApplicationContext().getSystemService(Page1.this.getActivity().LAYOUT_INFLATER_SERVICE);
format = inflater.inflate(R.layout.page1, null);
ll.addView(format);
//Lib.ShowAlertMessage(Page1.this.getActivity().getApplicationContext(), "", ""+format.getId());
if(Lib.result[no_of_count[m]][2].toString().equals("First Flight Couriers"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/first_flight";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
else if(Lib.result[no_of_count[m]][2].toString().equals("SkyNet WorldWide Express"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/skynet";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
else if(Lib.result[no_of_count[m]][2].toString().equals("The Professional Couriers"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/professional";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
else if(Lib.result[no_of_count[m]][2].toString().equals("The Professional Couriers"))
{
ImageView imageView1=(ImageView)rootView.findViewById(R.id.imageView1);
String uri = "#drawable/professional";
int imageResource = getResources().getIdentifier(uri, null, Page1.this.getActivity().getApplicationContext().getPackageName());
Drawable res = getResources().getDrawable(imageResource);
imageView1.setImageDrawable(res);
}
TextView textView2=(TextView)rootView.findViewById(R.id.textView2);
textView2.setText("Rupees");
}
if(format.getId()==1)
{
ll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intentx;
intentx = new Intent(Page1.this.getActivity(), From.class); //mContext is a Context variable.
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
if(format.getId()==2)
{
ll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intentx;
intentx = new Intent(Page1.this.getActivity(), To.class);
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
return rootView;
}
public void onResume(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
}
}
My Issue
1. I use these variables(Lib.results[][]) in the PostExecute They are available ( I dont require here)
2. In the fragment Page1 i am not able access the Lib.results[][] , as soon as it enters the Page1 the value of result[][] is null as the value is not updated(this is what I guessed would have hapened)
3. The results based on the values will go to respective fragments (Page1,Page2,Page3)
Question
Am i calling the fragment activity the rightway?? does intent work this way or is there any other method.
I figured that I had used the array as String but changing it to strArray made it work
I'm working viewpager and pagertitlestrip.i successfully created it and i wan add views in my viewpager.this is a my source
private ViewPager mViewPager;
TextView text;
private PagerTitleStrip mPagerTitleStrip;
View view1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mViewPager = (ViewPager)findViewById(R.id.viewpager);
mPagerTitleStrip = (PagerTitleStrip)findViewById(R.id.pagertitle);
//View
LayoutInflater mLi = LayoutInflater.from(this);
view1 = mLi.inflate(R.layout.activity_main, null);
text=(TextView)view1.findViewById(R.id.textView1);
//Title
final ArrayList<View> views = new ArrayList<View>();
final ArrayList<String> titles = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
view1 = mLi.inflate(R.layout.activity_main, null);
text=(TextView)view1.findViewById(R.id.textView1);
text.setText("Page"+i);
views.add(view1);
titles.add("title"+i);
}
mPagerTitleStrip.setTextColor(Color.BLUE);
//ViewPager
PagerAdapter mPagerAdapter = new PagerAdapter() {
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager)container).removeView(views.get(position));
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
#Override
public Object instantiateItem(View container, int position) {
((ViewPager)container).addView(views.get(position));
return views.get(position);
}
};
mViewPager.setAdapter(mPagerAdapter);
}
}
now i try to write pagertitlestrip's onclicklistener.for more information,if i click 4's title i would to start(show) 4th view.onclick listener by position
how i can solve my problem?
if anyone knows solution please help me
If you want to set view manually by tapping on some indicator the you can use this
mViewPager.setCurrentItem(num);
but if you want to do something when some page is selected the you can use
ViewPager.SimpleOnPageChangeListener
for the listener understanding you can follow this
ViewPager.SimpleOnPageChangeListener
Hope this will help
I have a viewpager with image fragments in it that works but on back was getting an error saying that there is no empty constructor. I made one but now my images don't show up because imageResourceId is null. I've tried a million things and can't figure it out.
public final class TestFragment extends Fragment {
String imageResourceId;
public TestFragment() {
}
public TestFragment(String cONTENT) {
imageResourceId = cONTENT;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
new DownloadImageTask((ImageView) image).execute(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
class TestFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
public String[] CONTENT;
private int mCount;
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar, R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms, R.drawable.perm_group_location };
public TestFragmentAdapter(FragmentManager fm, JSONArray photoData) {
super(fm);
// photoData = (JSONArray) userProfile.get("photos");
CONTENT = new String[photoData.length()];
mCount = photoData.length();
for (int i = 0; i < photoData.length(); i++) {
JSONObject mainPhoto;
try {
mainPhoto = photoData.getJSONObject(i);
CONTENT[i] = mainPhoto.getString("src_big");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
return new TestFragment(CONTENT[position]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
in the activity
mAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), photoData);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (LinePageIndicator) findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
Android uses the empty constructor of a fragment to restore the fragment when there is a configuration change, that's why you can't modify it, and you can't override it because you get an error in eclipse. The best practice to pass arguments to a fragment, when instantiating it, is to use an static factory method:
public class TestFragment extends Fragment {
String imageResourceId;
public static TestFragment newInstance(String resource) {
TestFragment f = new TestFragment();
Bundle args = new Bundle();
args.putString("Resource", resource);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageResourceId = getArguments().getString("Resource");
}
}
To instanciate it you use the static method:
TestFragment fragment = TestFragment.newInstance("some string");