where can I write the java code in fragments? - android

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

Related

Why on calling first fragment second fragment is automatically getting called?

I am using ViewPager to show 4 fragments but the problem is that on loading first fragment second fragment is also getting called i.e. the onActivityCreate() method of both the fragments is getting called together and on swiping to second fragment third fragment's onActivityCreate() and so on for other fragments and for last fragment no onActivityCreate() is getting called. How to resolve that.
Here are my files:
Purchase Details
public class PurchaseDetails extends AppCompatActivity implements ActionBar.TabListener {
ViewPager viewPager;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase_details);
viewPager=findViewById(R.id.master_purchase_pager);
FragmentManager fm=getSupportFragmentManager();
actionBar = getSupportActionBar();
actionBar.setTitle("Purchase Details");
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setAdapter(new PurchaseFragmentAdapter(fm));
viewPager.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) {
}
});
ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("Date Selector");
tab1.setTabListener(this);
ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("Week");
tab2.setTabListener(this);
ActionBar.Tab tab3 = actionBar.newTab();
tab3.setText("Month");
tab3.setTabListener(this);
ActionBar.Tab tab4 = actionBar.newTab();
tab4.setText("Year");
tab4.setTabListener(this);
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
actionBar.addTab(tab4);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
}
PurchaseFragmentAdapter
public class PurchaseFragmentAdapter extends FragmentPagerAdapter {
public PurchaseFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
if(position==0)
{
fragment= new PurchaseDateSelector();
}
else if(position==1)
{
fragment= new PurchaseWeek();
}
else if(position==2)
{
fragment= new PurchaseMonth();
}
else if(position==3)
{
fragment= new PurchaseYear();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
}
PurchaseDateSelector
public class PurchaseDateSelector extends Fragment
{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.purchase_date_selector_fragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "Purchase Date Selector", Toast.LENGTH_SHORT).show();
}
}
PurchaseWeek
public class PurchaseWeek extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.purchase_week_fragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "Purchase Week", Toast.LENGTH_SHORT).show();
}
}
PurchaseMonth
public class PurchaseMonth extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.purchase_month_fragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "Purchase Month", Toast.LENGTH_SHORT).show();
}
}
PurchaseYear
public class PurchaseYear extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.purchase_year_fragment,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "Purchase Year", Toast.LENGTH_SHORT).show();
}
}
The ViewPager doesn’t create all its pages at once. When using a lot of pages this would be horribly slow and even unnecessary if the user would never swipe through all these pages. By default the ViewPager only creates the current page as well as the off-screen pages to the left and right of the current page.
So what is solution of this problem, Is their any?
yeah there is,
mViewPager.setOffscreenPageLimit(int limit);
Parameters : limit – How many pages will be kept offscreen in an idle
state.
ViewPager require a minimum of 1 offscreen pages
If you set value to 0 then you should be getting a warning about this in LogCat, something like:
Requested offscreen page limit 0 too small;
defaulting to1
Its because ViewPager is based on concept of keep ready next page to be loaded. ViewPager can not the page which not exist still.
Thanks to Tech Code Geek
This is how ViewPager has been designed to work. By default the ViewPager only creates the current page as well as the off-screen pages to the left and right of the current page. This is to allow smooth transition between the pages.
You can also set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state.
Read More
That's the default and expected behavior of view pager, it creates each fragment to its left and right along with the visible fragment for smooth animations, you can't restrict fragment from creation, may be what you can do is restrict the loading content on non-visible fragments using setuserVisibleHint() method
#Override
public void setUserVisibleHint(boolean visible){
if(visible){
//load content
}
}

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

Change number of buttons in Fragment on Tab click

I have created 10 tabs programmatically and want to change number of buttons that are placed in fragment when a tab is clicked by user.
My 'MainActivity' code:
public class MainActivity extends Activity {
int numberOfButtons=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fragmentA = new FragmentA();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.mainLayout,fragmentA,"fragA");
transaction.commit();
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=0;i<10;i++)
{
ActionBar.Tab tab = actionBar.newTab().setText("Tab"+i).setTabListener(new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
numberOfButtons = 10;
sendNumber(numberOfButtons);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
});
actionBar.addTab(tab);
}
}
This is my fragment code:
public class FragmentA extends Fragment implements View.OnClickListener{
Button btn;
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int numberOfButtons= getArguments().getInt("someInt",0);
LinearLayout view = new LinearLayout(getActivity());
// Inflate the layout for this fragment
view.setOrientation(LinearLayout.VERTICAL);
view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
for (int i = 0;i<numberOfButtons;i++)
{
btn = new Button(getActivity());
view.addView(new Button(getActivity()));
}
myView = view;
return myView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
}
}
I am calling the numbeOfButtons method inside the MainActivity and want to send number of buttons to Fragment when a tab is clicked. However the application throws error after line fA.numberOfBtns(numberOfButtons); is called. The error is reflect.InvocationTargetException.
How can I change the number of buttons in Fragment when a tab is clicked?
You may want to use newInstance technique to pass parameters during Fragment initialization. Here is a small example taken from here:
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("someInt", someInt);
myFragment.setArguments(args);
return myFragment;
}
And later you can access this parameter:
getArguments().getInt("someInt", 0);

Action bar tabs

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

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