Action bar tabs - android

im trying to use action bar tabs and i have some questions.
I see from the developers blog that i need to use Fragment layout. I have in my wanted layout buttons that the margins between them is depends on the screen size.
I used to do in Relative layout but in Fragment layout it doest work.
Is there a way to change the view position from the java code?
My views dont respone to setOnClickListener anymore.
I tried using this code:
View homePageLayout = View.inflate(this, R.layout.home_page, null);
workoutWall = (ImageButton) homePageLayout.findViewById(R.id.workoutWall);
workoutWall.setOnClickListener(this);
And my fragemnts code:
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(tab.getPosition() == 0)
{
ft.add(R.id.fragment_place, fragmentHome, null);
setTheMarging();
}
else
ft.add(R.id.fragment_place, fragmentExtra, null);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current tab position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current tab position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
public static class HomePageFragment extends Fragment
{
public static final String ARG_SECTION_NUMBER = "placeholder_text";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.home_page, container, false);
}
}
public static class ExtrasFragment extends Fragment
{
public static final String ARG_SECTION_NUMBER = "placeholder_text";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.extras, container, false);
}
}
Thanks for helping

Related

how to display toast messages for each tab in swipe tab in android?

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
}
}

Android ActionBar TabNavigation switching between tabs clears View

I'm trying to convert my app to TabNavigation layout using this tutorial. First and last tab layout are always the same(just content changes), only second is different in every app. So I want from second tab manage others, e.g. in first one is imageView and from second tab I can firstTab.imageView.setImageResources(/somePic) to display some picture. It works fine but I noticed that app starts on tab1 and show picture, then I switch to tab2 and back to tab1, it's still there, but when I go to tab3->tab1 or tab3->tab2->tab1 the pictire is gone, so I have to go tab2->tab1
again to set the picture. Why is it happening and how to avoid that? I'm a begginer in android so thanks a lot for any help.
TabActivity:
public class TabActivity extends FragmentActivity {
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("Podgląd").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Dane").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Rozwiązanie").setTabListener(tabListener));
}
}
TabPagerAdapter:
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragement for Android Tab
return new Review();
case 1:
//Fragment for Ios Tab
return new Data();
case 2:
//Fragment for Windows Tab
return new Solution();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3; //No of Tabs
}
}
Data class(second tab)
public class Data extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View ios = inflater.inflate(R.layout.ios_frag, container, false);
((TextView)ios.findViewById(R.id.textView)).setText("iOS");
Review.imageView.setImageResource(R.drawable.ic_launcher);
return ios;
}}
Review class(first tab)
public class Review extends Fragment {
public static ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.android_frag, container, false);
//((TextView)android.findViewById(R.id.textView)).setText("Android");
imageView = (ImageView)android.findViewById(R.id.imageView);
return android;
}
}
Solution class(third tab)
public class Solution extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View windows = inflater.inflate(R.layout.windows_frag, container, false);
((TextView)windows.findViewById(R.id.textView)).setText("Windows");
return windows;
}}
I have read now about sending data with Bundle cause it saves app state but it doesn't work, I think it's because tab classes doesn't extends Activity, am I wrong?

Fragment showing contet twice

I'll explain the structure of my app :
Activity --> Fragment A (Inside that fragment (A) i have 3 Fragments (B, C, D) (viewpager)) --> Inside the first fragment(B) it contains a listview. Every item from that list launches a fragment E.
So i'm facing an issue here.
When i first launch my application Everything looks fine.
But when Fragment E get's visible to the screen the tabs gets all weird and be like :
Yeap! they got duplicated.
When i click on the listview, i commit the transition between the 2 fragments from a callback in the Activity :
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, PF);
transaction.addToBackStack(null);
transaction.commit();
When i want to go back to the previous fragment:
getFragmentManager().popBackStack();
Is the previous fragment getting recreated? And what can i do to solve it?
UPDATE --CODES:
Activity :
public class MainActivity extends FragmentActivity implements
IslamToolsFragment.OnToolsSelectedListener {
FragmentTransaction transaction;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.content_frame) != null) {
if (savedInstanceState != null) {
return;
}
PagerActivity firstFragment = new PagerActivity();
getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame, firstFragment).commit();
}
}
#Override
public void OnToolSelected(int position) {
// TODO Auto-generated method stub
switch (position) {
case 0:
PrayerFragment PF = new PrayerFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, PF);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
QiblaFragment QF = new QiblaFragment();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, QF);
transaction.addToBackStack(null);
transaction.commit();
break;
}
}
Fragment A (Which contains 3 fragments):
public class PagerActivity extends Fragment implements ActionBar.TabListener {
int NUM_PAGES = 5;
ActionBar actionBar;
private ViewPager mPager;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mPager.setAdapter(null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
return;
} else {
actionBar = this.getActivity().getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
getChildFragmentManager());
mPager.setAdapter(mAppSectionsPagerAdapter);
int icons[] = { R.drawable.ic_action_storage,
R.drawable.ic_action_overflow, R.drawable.ic_action_person };
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setIcon(icons[i])
.setTabListener(this));
}
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View tabsview = inflater.inflate(R.layout.pager_activity, container,
false);
mPager = (ViewPager) tabsview.findViewById(R.id.pager);
return tabsview;
}
Fragnent B:
public class IslamToolsFragment extends Fragment {
OnToolsSelectedListener mCallback;
ListView islamtools;
Fragment PF = new PrayerFragment();
public interface OnToolsSelectedListener {
public void OnToolSelected(int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View islamtoolsview = inflater.inflate(R.layout.lvislamtools,
container, false);
if (savedInstanceState != null) {
return islamtoolsview;
}
islamtools = (ListView) islamtoolsview.findViewById(R.id.lvislamtools);
String[] title = { "Prayer Times", "Qibla", "Ahadith", "Quran",
"Hijri Calendar", "99 Names" };
IslamToolsAdapter ITA = new IslamToolsAdapter(this.getActivity(), title);
islamtools.setAdapter(ITA);
islamtools.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mCallback.OnToolSelected(arg2);
}
});
return islamtoolsview;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnToolsSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
Thanks! is it something related to the savedinstancestate?
Your code design is a little bit wrong, fragments are actually pieces of activities, it does not make sense to me to create a fragment with more fragments inside in this situations, what you should do is create an activity for the viewpager and put into that activity your 3 fragments.
I have a similar app and this is how i handle the navigation between tabs:
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
The above code changes the item selected of the action bar BUT does not change the view below the view pager tabs, you need to implement the following to do this:
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

where can I write the java code in fragments?

iam a beginner in android
i wanted to make tabs
i took the sample and edited it to make a layout for every tab
but i couldn't find where to put the listeners of buttons of each layout of each tab in the code !
public class Game extends FragmentActivity implements ActionBar.TabListener {
static int Tab_no ;
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setTag("round").setText("Round").setTabListener(this));
actionBar.addTab(actionBar.newTab().setTag("score").setText("Score").setTabListener(this));
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) { // 3ashan law rege3na men ay makan yrg3ny le mkany
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) { // 3ashan law killed yrg3ny tany le makany
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
getActionBar().getSelectedNavigationIndex());
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the container
Fragment fragment = new SectionFragment();
Tab_no = tab.getPosition() + 1 ;
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class SectionFragment extends Fragment {
public SectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (Tab_no==1)
{
return inflater.inflate(R.layout.round , container, false);
}
else {
return inflater.inflate(R.layout.score , container, false);
}
}
}
}
and sorry for my bad english ! :)
You can write within onCreateView()
public class fragmentname extends Fragment{
Activity referenceActivity;
View parentHolder;
Button backBtn;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
referenceActivity = getActivity();
parentHolder = inflater.inflate(R.layout.yourlayout, container,
false);
backBtn = (Button) parentHolder.findViewById(R.id.back_btn);
backBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return parentHolder;
}
}

Android SherlockFragmentActivity call SherlockFragment

Originally, I have 2 Activities. A call B activities. Now I changed the A class extends SherlockFragmentActivity and B class extends SherlockFragment.
I tried to changed these in A class:
private class MyTabListener implements ActionBar.TabListener {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getPosition()==1) {
B frag = new B();
ft.replace(android.R.id.content, frag);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
//=============================
In B class:
public class Br extends SherlockFragment{
/* Called when the activity is first created */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.promotionslist_tableview);
//get our listview
ListView myListView = (ListView) findViewById(R.id.myListView_promotionslist_table);
//==============================
BUT ERROR.
1. onCreate
2. findViewById..
What i am wrong ?
please give me some hints. Thanks.
I can now display the B fragement but the listview overlap on the main listview..?
Why ?
public class B extends SherlockFragment{
View view;
/* Called when the activity is first created */
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//setContentView(R.layout.promotionslist_tableview);
//get our listview
ListView myListView = (ListView) view.findViewById(R.id.myListView_promotionslist_table);
.
.
.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.promotionslist_tableview, container, false);
return view;
}
You have to use the onCreateView() method in fragments:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout, null);
return view;
}
There you can inflate a View and call findViewById like this:
view.findViewById(...);

Categories

Resources