Button inside fragment - android

I'm hoping someone can help me with this extremely annoying problem. I'm new to working with fragments. I've have spend two days trying to get buttons to work inside my fragment. My app is a tab activity with sliding fragments auto created by android studio. I can change fragments by sliding and using the tabs. But I cannot get the buttons to respond. My app does not crash and my Log.e doesn't get registered in Logcat. I have copied lots of examples from the internet, but nothing seems to work.
I have tried implementing View.OnClickListener and not implementing it but nothing works. I'll post two examples that should work, but they don't.
FRAGMENT without implementing View.OnClickListener
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_summary_loggs, container, false);
Button test = (Button) rootView.findViewById(R.id.testButton);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("DEBUGG", "BUTTON PRESSED");
}
});
return rootView;
FRAGMENT with implementing View.OnClickListener
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_summary_loggs, container, false);
Button test = (Button) rootView.findViewById(R.id.testButton);
test.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.testButton:
Log.e("DEBUGG", "BUTTON PRESSED");
break;
}
}
This is only two examples of many that I have tried and it is driving me crazy. On all the examples on internet they all get them to work. My buttons simply won't respond when I press them. I will be extremely thankful if you could help me with this.
Layoutfile
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="xxxxxx.SummaryLoggs">
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/hello_blank_fragment3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:id="#+id/testButton"
android:layout_gravity="center" />
</FrameLayout>
ACTIVITY where i swipe fragments view
import...
public class AmLogger extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
Handler customHandler = new Handler();
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_am_logger);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_am_logger, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
private int mPosition;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPosition = getArguments().getInt(ARG_SECTION_NUMBER);
Log.e("DEBUGG", "mPosition: " + mPosition);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_summary_loggs, container, false);
switch (mPosition) {
case 1:
rootView = inflater.inflate(R.layout.fragment_add_time, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_item_list, container, false);
break;
}
return rootView;
}
}
}

I think you're not creating 3 fragments. You should have 3 fragment classes in your activity one for each tab and also depending upon design for each fragment, you need to have 3 layout files. Then declare the button in your appropriate layout file and use it in your Fragment class as shown below.
public class AmLogger extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
Handler customHandler = new Handler();
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_am_logger);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_am_logger, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// AddTime fragment
return AddTime.newInstance(position + 1);
case 1:
// MyLogs fragment
return MyLogs.newInstance(position + 1);
case 2:
// SummaryLogs fragment
return SummaryLogs.newInstance(position + 1);
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
//AddTime fragment
public static class AddTime extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static AddTime newInstance(int sectionNumber) {
AddTime fragment = new AddTime();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public AddTime() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_addtime, container, false);
return rootView;
}
}
//MyLogs Fragment
public static class MyLogs extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static MyLogs newInstance(int sectionNumber) {
MyLogs fragment = new MyLogs();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public MyLogs() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_mylogs, container, false);
return rootView;
}
}
//SummaryLogs fragment
public static class SummaryLogs extends Fragment implements View.OnClickListener{
private static final String ARG_SECTION_NUMBER = "section_number";
public static SummaryLogs newInstance(int sectionNumber) {
SummaryLogs fragment = new SummaryLogs();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public SummaryLogs() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_summarylogs, container, false);
//Code to get the button from layout file
Button btn = (Button) rootView.findViewById(R.id.testButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Implement the code to run on button click here
}
});
return rootView;
}
}
}

Related

Change Fragment in a tabbed Activity with a Button

I'm developing an application in which I have to implement a function that allows to me to change a Fragment with a Button instead of crawling the site on the screen.
Tutorial.java
public class Tutorial extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
PlaceholderFragment.java
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tutorial, container, false);
Button next = (Button) rootView.findViewById(R.id.next);
Button previous = (Button) rootView.findViewById(R.id.previous);
RelativeLayout rl = (RelativeLayout) rootView.findViewById(R.id.relative_tutorial);
switch (getArguments().getInt(ARG_SECTION_NUMBER)){
case 1:
rl.setBackgroundResource(R.drawable.one);
previous.setText("ESCI");
previous.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getActivity().finish();
}
});
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
break;
case 2:
rl.setBackgroundResource(R.drawable.two);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
break;
case 3:
rl.setBackgroundResource(R.drawable.three);
next.setText("HOME");
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getActivity().finish();
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
}
});
break;
}
return rootView;
}
}
SectionsPagerAdapter.java
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
How I can switch "page" by clicking my Button, instead of crawling the site on the screen?
This is how you display another fragment. So, just put this code inside your buttons onclick method.
Example:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(android.R.id.content, new Fragment_1(), "frag1");
fragmentTransaction.commit();

Application crashes after 3rd fragment?

On tab, I have attached five fragments.Till 3rd fragment navigation is fine but when going to 4th and 5th fragment directly or by swiping, app is getting crashed.
This is my main activity.
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Videos"));
tabLayout.addTab(tabLayout.newTab().setText("Games"));
tabLayout.addTab(tabLayout.newTab().setText("Maps"));
tabLayout.addTab(tabLayout.newTab().setText("Quizze"));
tabLayout.addTab(tabLayout.newTab().setText("Discussion"));
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm, int tabCount) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Videos tab1 = new Videos();
return tab1;
case 1:
Notes tab2 = new Notes();
return tab2;
case 2:
MindMaps tab3 = new MindMaps();
return tab3;
case 3:
Quizze tab4 = new Quizze();
return tab4;
case 5:
Discussion tab5 = new Discussion();
return tab5;
}
return null;
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
case 3:
return "SECTION 4";
case 4:
return "SECTION 5";
}
return null;
}
}
}
This is my fragment class which is right now same for all the five fragments except the class name).
public class Videos extends android.support.v4.app.Fragment {
public static Videos newInstance() {
Videos fragment = new Videos();
return fragment;
}
public Videos() {
}
Button ClickMe;
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.video, container, false);
ClickMe = (Button) rootView.findViewById(R.id.button);
tv = (TextView) rootView.findViewById(R.id.textView2);
ClickMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(tv.getText().toString().contains("Hello")){
tv.setText("Hi molu");
}else tv.setText("Hello");
}
});
return rootView;
}
} // This is the end of our MyFragments Class
Case 4 is missing in your adapter. Add the Case 4 instead of 5 then it will work fine.

android - textswitcher in fragment

Using horizontalpaging example in android studio,
i put two activities, Tab1.Java and Tab2.Java.
And i want to put textswitcher in both activity.
But, TextView(Tab1.this) in Tab1.Java is make an error.
And i think it has another problems.
How can i make this codes work?
MainActivity.Java
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
Context mContext;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new Tab1(mContext);
case 1:
return new Tab2(mContext);
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}}
Tab1.Java
public class Tab1 extends Fragment {
Context mContext;
public Tab1(Context context) {
mContext = context;
}
private TextSwitcher mSwitcher;
Button button1;
String textToShow[]={"st1","st2","st3","st4","st5","st6"};
int messageCount=textToShow.length;
int currentIndex=-1;
public View onCreateView(LayoutInflater inflater,
ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.activity_tab1, null);
super.onCreate(savedInstanceState);
button1=(Button)view.findViewById(R.id.button1);
mSwitcher = (TextSwitcher) view.findViewById(R.id.textSwitcher);
mSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
TextView myText = new TextView(Tab1.this);
myText.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
myText.setTextSize(36);
return myText; }});
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
currentIndex++;
// If index reaches maximum reset it
if (currentIndex == messageCount)
currentIndex = 0;
mSwitcher.setText(textToShow[currentIndex]);
}});
return view; }
}
activity_tab1.xml
<TextSwitcher
android:layout_marginTop="50dp"
android:id="#+id/textSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:singleLine="false"
android:typeface="normal" />

Android tab fragment not calling OnCreateView switching from tab2 to tab1

This is the autogenerated code from android studio when selecting a 3 tabbed layout. The problem is when it starts at the first tab, it will call onCreateView in class PlaceholderFragment. When i switch to the 2nd tab, it calls it again for that tab. Now the problem starts with going back to tab1, it doesn't call onCreateView. Now if i go to tab3 it gets called for that tab, then go back to tab1 it now gets called. So tab1's onCreateView never gets called if i go from tab2 to tab1 but gets called going from tab3 to tab1. I can't figure out why it doesn't destroy this view in that specific sequence only.
I haven't modified this auto-generated code so i'd think it would have worked correctly.
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Viewpager has one public method named setOffScreenPageLimit() which indicates the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.
When you use the default implementation of setOffscreenPageLimit() it is only loading the one fragment which is to the right of it.
For example,
if you are currently on index1, it has index 2 loaded in memory but not index 0, so swiping to left will load a new fragment from scratch. Use setOffScreenLimit(1), setOffScreenLimit(2) etc. it will help clear out your doubts about the concept.

Action bar tabs with viewpager with different page layouts

Hi Im new in android and I want ask for help. Im creating new project in android studio and I use navigation Action bar tabs with viewpager. Android studio generate this code. I know work with one activity atc but now I want to learn work with swipe layouts with tabs. My question is: Is possible do more layouts with different items inside this? For example, now I have on every fragment one textview and when I swipe I see any text on every page. But I need for example on page(tab1) layout with textview, on tab2 I need layout edittext, on tab3 I need layout with image. Is this possible with this? Because I can change text but now I have the same layout for all tabs.
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
In this case you can define 3 separate fragment classes. Then you can return them appropriately in getItem of your SectionsPagerAdapter:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new YourFragmentClass1();
case 1:
return new YourFragmentClass2();
case 2:
return new YourFragmentClass3();
}
}
To elaborate on Szymon's answer.
Step 1 Delete the inner class PlaceHolderFragment
Step 2: Create your fragment classes, with corresponding layouts. For example, ImageViewFragment (which extends Fragment of course) and then image_view_fragment_layout.
Step 3 Have ImageViewFragment's onCreateView method inflateimage_view_fragment_layout.
public ImageViewFragment extends Fragment {
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.image_view_fragment_layout,
container, false);
return rootView;
}
Follow these steps for as many tabs you want to add.
Then in the getItem() method follow Szymon's answer. Remember, the tab you want to appear first will be in position 0 and so on.
One more Important thing, in your getCount method:
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
the number returned should reflect the number of tabs you have added.

Categories

Resources