adding swipe in TabLayout (Tabs bar) - java

I can swipe between tabs but I want to keep many tabs but the tab bar just below the action bar is too cluttered. My screenshot. So I want to add a swipe feature in tab bar itself. Example
Here is my code:
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);
//sets custom toolbar as actionbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the two primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given 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;
}
#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;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
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 8 total pages.
return 8;
}
#Override
public CharSequence getPageTitle(int position) { //Gets the title of the tabs
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 2";
case 3:
return "SECTION 2";
case 4:
return "SECTION 2";
case 5:
return "SECTION 2";
case 6:
return "SECTION 2";
case 7:
return "SECTION 2";
// case 1:
// return "SECTION 2";
}
return null;
}
}

It is very simple, In your tabLayout put this attribute
app:tabMode="scrollable"
instead of
app:tabMode="fixed"
Hope this helps.

Related

Listview to the same activity with different text on tabbed activity

I'm new at Android programming and I need your help. Please.
What I want to do.
I created listview, from listview I created OnItemClickListener to TabbedActivity.
Now I want for each listview item to show different text on TabbedActivity.
This is MainActivity:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
listview = (ListView) findViewById(R.id.listview);
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.bolesti));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch (i){
case 0:
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(MainActivity.this, TabbedActivity.class);
startActivity(intent1);
break;
}
}
});
listview.setAdapter(mAdapter);
}}
TabbedActivity:
public class TabbedActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_tabbed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabbed, 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;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
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).
switch (position){
case 0:
Tab1Opis tab1 = new Tab1Opis();
return tab1;
case 1:
Tab2Simptomi tab2 = new Tab2Simptomi();
return tab2;
case 2:
Tab3Uzroci tab3 = new Tab3Uzroci();
return tab3;
case 3:
Tab4Lijecenje tab4 = new Tab4Lijecenje();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Opis";
case 1:
return "Simptomi";
case 2:
return "Uzroci";
case 3:
return "Lijecenje";
}
return null;
}
}}
TabbedActivity contains 4 tabs, all of them have different .java class example:
public class Tab2Simptomi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simptomi, container, false);
return rootView;
}}
I need to change text in every fragment when I click on different listview item.
Can you help me? Thank you.
Check the pictures. Thank you a lot.
You can pass text from your MainActivity to TabbedActivity fragment Tab2Simptomi as below:
1. Pass text from MainActivity to TabbedActivity, using Intent extras.
Update onItemClick() as below:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch (i){
case 0:
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
intent.putExtra("YOUR_TEXT", "Text One");
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(MainActivity.this, TabbedActivity.class);
intent1.putExtra("YOUR_TEXT", "Text Two");
startActivity(intent1);
break;
}
}
});
2. Pass text from TabbedActivity to Tab2Simptomi, setting bundle as arguments of fragments inside SectionsPagerAdapter.
In TabbedActivity onCreate() method, get text that was passed from MainActivity
public class TabbedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
// Get text
String text = getIntent().getStringExtra("YOUR_TEXT");
// Pass text to SectionsPagerAdapter
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), text);
.............
......................
}
}
Update SectionsPagerAdapter to pass text to Fragments:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private String yourText;
public SectionsPagerAdapter(FragmentManager fm, String yourText) {
super(fm);
this.yourText = yourText;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("YOUR_TEXT", yourText);
switch (position){
case 0:
Tab1Opis tab1 = new Tab1Opis();
tab1.setArguments(bundle); // Pass text to Tab1Opis fragment
return tab1;
case 1:
Tab2Simptomi tab2 = new Tab2Simptomi();
tab2.setArguments(bundle);
return tab2;
case 2:
Tab3Uzroci tab3 = new Tab3Uzroci();
tab3.setArguments(bundle);
return tab3;
case 3:
Tab4Lijecenje tab4 = new Tab4Lijecenje();
tab4.setArguments(bundle);
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Opis";
case 1:
return "Simptomi";
case 2:
return "Uzroci";
case 3:
return "Lijecenje";
}
return null;
}
}}
3. Finally get text from individual Frgament and do whatever you want.
Update Tab2Simptomi as below:
public class Tab2Simptomi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simptomi, container, false);
String finalText = getArguments().getString("YOUR_TEXT");
// Do something with finalText
Toast.makeText(getActivity(), "Final Text: " + finalText, Toast.LENGTH_SHORT).show();
return rootView;
}
}
UPDATE:
Assuming your fragment texts are static.
1. Pass texts from MainActivity to TabbedActivity, using Intent extras.
Update onItemClick() as below:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch (i){
case 0:
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
intent.putExtra("OPIS", "Item1 :: Text for Fragment OPIS");
intent.putExtra("SIMPTOMI", "Item1 :: Text for Fragment SIMPTOMI");
intent.putExtra("UZROCI", "Item1 :: Text for Fragment UZROCI");
intent.putExtra("LIJECENJE", "Item1 :: Text for Fragment LIJECENJE");
startActivity(intent);
break;
case 1:
Intent intent1 = new Intent(MainActivity.this, TabbedActivity.class);
intent1.putExtra("OPIS", "Item2 :: Text for Fragment OPIS");
intent1.putExtra("SIMPTOMI", "Item2 :: Text for Fragment SIMPTOMI");
intent1.putExtra("UZROCI", "Item2 :: Text for Fragment UZROCI");
intent1.putExtra("LIJECENJE", "Item2 :: Text for Fragment LIJECENJE");
startActivity(intent1);
break;
}
}
});
2. Pass texts from TabbedActivity to Tab2Simptomi, setting bundle as arguments of fragments inside SectionsPagerAdapter.
In TabbedActivity onCreate() method, get text that was passed from MainActivity
public class TabbedActivity extends AppCompatActivity {
ArrayList<String> stringArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
stringArray = new ArrayList<String>();
// Get texts
String textOPIS = getIntent().getStringExtra("OPIS");
String textSIMPTOMI = getIntent().getStringExtra("SIMPTOMI");
String textUZROCI = getIntent().getStringExtra("UZROCI");
String textLIJECENJE = getIntent().getStringExtra("LIJECENJE");
// Add text to ArrayList
stringArray.add(textOPIS);
stringArray.add(textSIMPTOMI);
stringArray.add(textUZROCI);
stringArray.add(textLIJECENJE);
// Pass ArrayList to SectionsPagerAdapter
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), stringArray);
.............
......................
}
}
Update SectionsPagerAdapter to pass text to Fragments:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<String> stringList;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<String> stringArray) {
super(fm);
this.stringList = stringArray;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("YOUR_TEXT", stringList.get(position)); // Get string from stringList using position
switch (position){
case 0:
Tab1Opis tab1 = new Tab1Opis();
tab1.setArguments(bundle); // Pass text to Tab1Opis fragment
return tab1;
case 1:
Tab2Simptomi tab2 = new Tab2Simptomi();
tab2.setArguments(bundle);
return tab2;
case 2:
Tab3Uzroci tab3 = new Tab3Uzroci();
tab3.setArguments(bundle);
return tab3;
case 3:
Tab4Lijecenje tab4 = new Tab4Lijecenje();
tab4.setArguments(bundle);
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Opis";
case 1:
return "Simptomi";
case 2:
return "Uzroci";
case 3:
return "Lijecenje";
}
return null;
}
}}
3. Finally get text from individual Frgament and do whatever you want.
Update Tab2Simptomi as below:
public class Tab2Simptomi extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simptomi, container, false);
String finalText = getArguments().getString("YOUR_TEXT");
// Do something with finalText
TextView yourTextView = (TextView) rootView.findViewById(R.id.your_textview);
// Show text on TextView
yourTextView.setText(finalText);
Toast.makeText(getActivity(), "Final Text: " + finalText, Toast.LENGTH_SHORT).show();
return rootView;
}
}
Hope this will help~
In MainActivity
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
switch (i){
case 0:
intent.putExtra("Title", "Title1");
break;
case 1:
intent.putExtra("Title", "Title2");
break;
}
startActivity(intent);
}
});
In TabbedActivity,String title is Title1 or Title2 based on what was clicked in MainActivity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
String title = getIntent().getStringExtra("Title");
Toast.makeText(this, ""+title, Toast.LENGTH_SHORT).show();
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
}

Showing different xmls by tabView

I've created a tab view by Android Studio, this is the default code for MainActivity.java:
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
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);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given 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;
}
#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;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
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) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
so I have three xmls:
one.xml
two.xml
fragment_main.xml
I want to change the layout of each tab to an unique xml that I mentioned.
I tried this way:
Added this to my MainActivity.java:
public class FrChange extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.one, container, false);
return rootView;
}
}
and then I changed this:
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;
to this:
return new FrChange();
But it throws me bunch of errors.
What should I do?
My problem was with the adapter.
Check out link for further information : different layout for each tab

add fragment to pager adapter on button click

I have a tabbed activity with 1 fragment, this fragment has a button, i want when i click the button it create a new fragment and i can swipe between the two fragments
this is the main activity
public class ActivityBeamRec extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
public static CustomViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_beam_rec);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (CustomViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPagingEnabled(false);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0 : return PlaceholderFragment.newInstance(position + 1);
// case 1 : return the new fragment ;
}
return null;
}
#Override
public int getCount() {
return 1 ;
}
}
}
this is the fragment i have.
public class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);
final EditText etxb;
etxb = (EditText)rootView.findViewById(R.id.editText);
final Button buDesign = (Button)rootView.findViewById(R.id.buDesign);
buDesign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double b;
b = Double.valueOf(etxb.getText().toString());
\\here i want the button to create the second fragment and pass the variable d to it
ActivityBeamRec.mViewPager.setPagingEnabled(true); // this is to enable the siwpe between the fragments
ActivityBeamRec.mViewPager.setCurrentItem(2); // ths is to set the new fragment as the current view
}
});
return rootView;
}
}
the second fragment should go through on create view stage after the button is pressed, and please tell where i put each code if there is a way to do this.
ActivityBeamRec:
public class ActivityBeamRec extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
// This list holds the fragments for the pages displayed by view pager.
private List < Fragment > fragments = new ArrayList < Fragment > ();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
// Add the first fragment:
fragments.add(PlaceholderFragment.newInstance(1));
}
private void addFragment(Fragment fragment) {
fragments.add(fragment);
// Notify view pager that the contents of the adapter has changed and that it needs to update
// its pages:
notifyDataSetChanged();
// Since content of view pager has changed, re-wire tab layout:
tabLayout.setupWithViewPager(mViewPager);
// Set the current page in the view pager to the last added fragment:
mViewPager.setCurrentItem(fragments.size() - 1);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
// Set the tab title as the number of the current section:
return "SECTION " + (position + 1);
}
}
/**
* Adds a new fragment (page) to the view pager.
* This method can either be public or package-private (without any modifier) depending on the package
* of 'PlaceholderFragment'. Since you're new to Java please refer the link to access modifiers below.
*
* #param fragment the fragment to be added to the view pager
**/
public void addFragment(Fragment fragment) {
mSectionsPagerAdapter.addFragment(fragment);
}
/**
* Returns the number of the next section (page) to be added.
*
* #return the next section number
*/
public int getNextSectionNumber() {
return mSectionsPagerAdapter.getCount() + 1;
}
}
PlaceholderFragment:
public class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {}
/**
* Returns a new instance of this fragment for the given 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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);
final EditText etxb;
etxb = (EditText) rootView.findViewById(R.id.editText);
final Button buDesign = (Button) rootView.findViewById(R.id.buDesign);
buDesign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double b;
b = Double.valueOf(etxb.getText().toString());
//here i want the button to create the second fragment and pass the variable d to it
int nextSectionNumber = ((ActivityBeamRec) getActivity()).getNextSectionNumber();
((ActivityBeamRec) getActivity()).addFragment(PlaceholderFragment.newInstance(nextSectionNumber));
}
});
return rootView;
}
}
When the button in the fragment is clicked the following things occur in sequence:
addFragment() method of parent activity is called by passing the fragment instance to be added. This public method is used to access the private member mSectionsPagerAdapter of parent activity. We can do away with this method if mSectionsPagerAdapter is made public or package-private.
SectionsPagerAdapter adds the passed-in fragment to its list of fragments and then notifies the view pager that its data set has changed.
TabLayout is refreshed to accommodate the new fragment (page).
Finally the view pager is made to scroll to the added fragment using the setCurrentItem() method.
Reference:
Java Access Control Modifiers
List Data Structure in Java
In your SectionsPagerAdapter
private ArrayList<Fragment> fragments = new ArrayList<>();
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
if(position<fragments.size())
return fragments.get(position);
throw new NullPointerException("No Fragment with this position found.");
}
public void addFragment(Fragment newFragment){
fragments.add(newFragment);
}
In the MainActivity before setting the adapter with mViewPager.setAdapter(mSectionsPagerAdapter); add your first fragment(the PlaceHolder in your case). (or do it in the SectionPagerAdapter's constructor).
And then in your OnClickListener call the SectionPagerAdapter's addFragment method.
EDIT: In MainActivity:
mSectionsPagerAdapter.addFragment(PlaceholderFragment.newInstance(0));
mSectionsPagerAdapter.setAdapter(mSectionsPagerAdapter);

How to add Tablayout icons

I have one question, how do I implement icons for tablayout.
I have 3 tabs and for all tabs I have icons selected and unselected. (White-Yellow color).
But, dunno how to implement those.
Here is mine UserActivity class:
public class UserActivity extends AppCompatActivity {
FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
adapterViewPager = new UserFragmentPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapterViewPager);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.selector));
}
UserFragmentPageAdapter:
public UserFragmentPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return SmallMoveFragment.newInstance(0, "Small Move");
case 1: // Fragment # 0 - This will show FirstFragment different title
return DeliveryFragment.newInstance(1, "Delivery");
case 2: // Fragment # 1 - This will show SecondFragment
return GarbageFragment.newInstance(2, "Garbage");
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return "Small Move";
case 1: // Fragment # 0 - This will show FirstFragment different title
return "Delivery";
case 2: // Fragment # 1 - This will show SecondFragment
return "Garbage ";
default:
return "No name";
}
}
}
And ONE of 3 tabs:
public class DeliveryFragment extends Fragment {
// Store instance variables
private String title;
private int page;
// newInstance constructor for creating fragment with arguments
public static DeliveryFragment newInstance(int page, String title) {
DeliveryFragment fragmentFirst = new DeliveryFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_delivery, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.DeliveryTxt);
tvLabel.setText(page + " -- " + title);
return view;
}
}
Any ideas where and how... I would do it with TabHost, but I would like it this way.
I have 6 icon 48x48 in drawable/hdpi.
There's a solution but not very well.
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int pos = tab.getPosition();
switch (pos) {
case 0 :
tab.setIcon(R.drawable.select_0);
break;
case 1 :
tab.setIcon(R.drawable.select_1);
break;
case 2 :
tab.setIcon(R.drawable.select_2);
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
int pos = tab.getPosition();
switch (pos) {
case 0 :
tab.setIcon(R.drawable.unselect_0);
break;
case 1 :
tab.setIcon(R.drawable.unselect_1);
break;
case 2 :
tab.setIcon(R.drawable.unselect_2);
break;
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
but this code may be in your User Activity, pagerAdapter doesn't support tab with icon directly.

Android Studio Tabbed Activity showing same content

I created a new android studio tabbed activity with viewpager ,but the three tabs are shwoinf thee same content that i put in the fragment here is my class
package com.mrad4tech.development.tabbedactivity;
import java.util.Locale;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity2Activity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
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_main_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
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) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
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;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given 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_activity2, container, false);
return rootView;
}
}
}
fragment_main_activity2: is the name of th fragment
I am not sure if I understand the question correctly.
Is it a piece of code you copied some where, and you want to understand where should you change in order to show different fragment?
If you want to show 3 totally different Fragment, you have to change SectionsPageAdapter.getItem(int position) to something like this
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (position) {
case 0:
return FragmentFirst.newInstance();
case 1:
return FragmentSecond.newInstance();
case 2:
return FragmentThird.newInstance();
default:
//assume you only have 3
throw new IllegalArgumentException();
}
}
and create the Fragment classes, and remember to create the corresponding layout xml as well, i.e. fragment_first.xml, fragment_second.xml, fragment_third.xml
public static class FragmentFirst extends Fragment {
public static FragmentFirst newInstance(int sectionNumber) {
FragmentFirst fragment = new FragmentFirst();
return fragment;
}
public FragmentFirst() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
}
public static class FragmentSecond extends Fragment {
public static FragmentSecond newInstance(int sectionNumber) {
FragmentSecond fragment = new FragmentSecond();
return fragment;
}
public FragmentSecond() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second, container, false);
return rootView;
}
}
public static class FragmentThird extends Fragment {
public static FragmentThird newInstance(int sectionNumber) {
FragmentThird fragment = new FragmentThird();
return fragment;
}
public FragmentThird() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_third, container, false);
return rootView;
}
}
Edit the whole SectionsPagerAdapter for reference
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
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.
switch (position) {
case 0:
return FragmentFirst.newInstance();
case 1:
return FragmentSecond.newInstance();
case 2:
return FragmentThird.newInstance();
default:
//assume you only have 3
throw new IllegalArgumentException();
}
}
#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;
}
}
You need to change your PlaceholderFragment to something like below.
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
// A field that contains your args value;
private int mSectionNumber;
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 void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Parses your arguments
if(getArguments() != null) {
mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_activity2, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Updates your view
((TextView) findViewById(R.id.text1)).setText("Section Number: " + mSectionNumber);
}
}

Categories

Resources