I'm new in android and I want to make a project, but I have a problem with inserting a list view inside fragment of tabbed activity which can pass to another activity when clicked. Before I asked here, I already tried to search the solution but it didn't work, I hope anyone in here can solve my problem.
Here's my code
Service Activity as a Tab host
public class ServiceActivity 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_service);
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_, 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);
}
//deleted PlaceHolderFragment
/**
* 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:
Sinspection sins = new Sinspection();
return sins;
case 1:
Minspection mins = new Minspection();
return mins;
case 2:
Linspection lins = new Linspection();
return lins;
case 3:
WRinspection wrins = new WRinspection();
return wrins;
default:
return null;
}
}
#Override
public int getCount() {
// Show total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "S Inspection";
case 1:
return "M Inspection";
case 2:
return "L Inspection";
case 3:
return "When Required";
}
return null;
}
}
Fragment Class
public class Linspection extends ListFragment {
String [] linsp = {
"Differential Oil and Filter",
"Hub and Reduction Gear Oil",
"Wheel Nut",
"Air Dryer Filter"
};
ArrayAdapter<String> adapter;
ListView listView;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
listView = (ListView)getActivity().findViewById(R.id.listViewL);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.
simple_list_item_1,linsp);
setListAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position){
case 0:
Intent intent = new Intent(getActivity(), EngineOil.class);
startActivity(intent);
}
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
I want to pass to this activity
public class EngineOil extends AppCompatActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.s_engine_oil);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
}
}
This is my xml:
activity_service
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listViewL"
>
</ListView>
</RelativeLayout>
activity destionation xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="?attr/actionBarTheme"
android:minHeight="?attr/actionBarSize"
android:id="#+id/toolbar3"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/viewPager"
android:layout_marginTop="20dp"
android:layout_below="#+id/toolbar3"
android:layout_alignParentStart="true">
</android.support.v4.view.ViewPager>
</RelativeLayout>
When I run the application it "always keep crashing". I don't know how to fix it, and hope you can help me to solve my problem
Thanks in advance
I made a project for you to use as reference.
`activity_main`
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabHost
android:id="#+id/tabHost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/ll_cashier_invoice"
android:baselineAligned="false"
android:gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="4dip">
<fragment
android:id="#+id/frag_invoice"
android:name="com.example.sydney.sample.MainActivity$FirstFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/tab4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
`fragment1.xml`
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/myArray" />
</LinearLayout>
`MainActivity.java`
public class MainActivity extends Activity {
ListView lv;
TabHost host;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
host = (TabHost)findViewById(R.id.tabHost);
host.setup();
lv = (ListView)findViewById(R.id.list);
TabHost.TabSpec spec = host.newTabSpec("Sinspection");
spec.setContent(R.id.tab1);
spec.setIndicator("Sinspection");
host.addTab(spec);
//Tab 2
spec = host.newTabSpec("Minspection");
spec.setContent(R.id.tab2);
spec.setIndicator("Minspection");
host.addTab(spec);
//Tab 3
spec = host.newTabSpec("Linspection");
spec.setContent(R.id.tab3);
spec.setIndicator("Linspection");
host.addTab(spec);
//Tab 4
spec = host.newTabSpec("Winspection");
spec.setContent(R.id.tab4);
spec.setIndicator("Winspection");
host.addTab(spec);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(MainActivity.this,NextActivity.class);
startActivity(myIntent);
}
});
}
public static class FirstFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
}
}
Click here for the full code.
Related
I've searched in many places and tried many solutions to the following problem, I hope you can help!
I've made a Tabbed Activity with 6 fragments, and a logging screen from a blank activity. The Tabbed activity is the main activity which has a ViewPager container to show the actual tab, however the logging activity is the first one to load and show. Somewhere along the process (very far into it actually) I've noticed that the fragments inside the container will occasionally wont show. They would sometimes reappear when I rotate the screen, or when I use the Logout feature from the menu and then login back in (sometimes takes several tries until is shows back up).
I've read through but could't figure it out.
I've tried changing the
(getChildFragmentManager(), getResources()));
but I think I don't place it in the right spot.
My MainActivty
public class MainActivity extends AppCompatActivity {
private boolean verified;
public static String token;
/**
* 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);
// Get the Intent that started this activity and extract the string
Bundle extras = getIntent().getExtras();
if (extras != null) {
verified = extras.getBoolean("verify");
token = extras.getString("token");
Toast.makeText(getBaseContext(), "Login Successful",
Toast.LENGTH_SHORT).show();
}
if(verified != true) {
logoutSuccessful();
}
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());
//mSectionsPagerAdapter.saveState();
// 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);
//getSupportActionBar().setIcon(R.drawable.logo_small);
//set icons for tabs
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if (i == 0) {
tabLayout.getTabAt(i).setIcon(R.drawable.icon_scan);
} else {
if (i == 1) {
tabLayout.getTabAt(i).setIcon(R.drawable.icon_pricecheck);
} else {
tabLayout.getTabAt(i).setIcon(R.drawable.logo_small);
}
}
}
}
#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;
}
if (id == R.id.action_logout) {
logoutSuccessful();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
//DELETED PLACEHOLDER CLASS
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
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);
switch (position){
case 0: Tab1 tab1 = new Tab1();
return tab1;
case 1: Tab2 tab2 = new Tab2();
return tab2;
case 2: Tab3 tab3 = new Tab3();
return tab3;
case 3: Tab4 tab4 = new Tab4();
return tab4;
case 4: Tab5 tab5 = new Tab5();
return tab5;
case 5: Tab6 tab6 = new Tab6();
return tab6;
}
return null;
}
#Override
public int getCount() {
// Show total pages.
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SCAN";
case 1:
return "PRICE CHECK";
case 2:
return "SECTION 3";
case 3:
return "SECTION 4";
case 4:
return "SECTION 5";
case 5:
return "SECTION 6";
}
return null;
}
}
private void logoutSuccessful(){
Intent myIntent = new Intent(MainActivity.this, Login.class);
MainActivity.this.startActivity(myIntent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
finish();
}
}
Tab1:
public class Tab1 extends android.support.v4.app.Fragment {
Button btnUpc;
EditText txtUPC;
Vector<UPCProductObject> v = new Vector<>();
Editable value;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab1, container,false);
lblUpcResult = (TextView) v.findViewById(R.id.lblUPCResult);
txtUPC = (EditText) v.findViewById(R.id.txtUPC);
btnUpc = (Button) v.findViewById(R.id.btnUPC);
btnUpc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
//hide keyboard
InputMethodManager mgr = (InputMethodManager)
getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(txtUPC.getWindowToken(), 0);
btnUpc.setEnabled(false);
value = txtUPC.getText();
new searchUPC().execute();
}});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
getChildFragmentManager().beginTransaction()
.add(R.id.container, new Tab1(), "Scan")
.commit();
}
}
activity_main xml:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.dabush.shen.mcrpos.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="90dp"
android:layout_height="50dp"
android:src="#drawable/logo_small"
android:layout_gravity="left"
/>
</FrameLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="75dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:minHeight="80dp">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/textColorPrimary"
app:tabTextColor="#FFD5D2D2" />
</android.support.design.widget.AppBarLayout>
<!--FLOATING EDITABLE BUTTON
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
-->
tab1 xml
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="13dp"
android:layout_toLeftOf="#+id/tblSearch"
android:layout_toStartOf="#+id/tblSearch" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab1_title"
android:textSize="24sp"
android:layout_alignTop="#+id/section_label"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="#string/scan_desc"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:id="#+id/tblSearch"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/txtUPC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:textAlignment="center" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="0dp">
<Button
android:id="#+id/btnUPC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SEARCH" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" />
</TableLayout>
<TextView
android:id="#+id/lblUPCResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tblSearch"
android:layout_centerHorizontal="true"
android:layout_marginTop="91dp"
android:textAlignment="center"
android:textSize="12sp" />
<ListView
android:id="#+id/listUpc"
android:layout_width="match_parent"
android:layout_height="375dp"
android:layout_below="#+id/tblSearch"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:textAlignment="center" />
You dont need to getChildFragmentManager().beginTransaction() in ur 1st fragment. And in activity lifecycle, onRotate, activity was destroyed and recreate, you need to save it on saveInstance and reload UI onRestoreInstance
i have a tabbed layout with fragments on each page. on the first page there is a user input box and button that when inputted and clicked gives a toast. i would like to store the string of data in my mysql database and populate the list view on another fragment with data stored in the table from mysql. Was wondering how to go about this exactly?
main activity class
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
public void btnShout(View v) {
//allows for label to be changed to shouted once button is pressed
EditText txtInput = (EditText) findViewById(R.id.txtInput);
TextView lblShout = (TextView) findViewById(R.id.lblShout);
lblShout.setText("Shouted! ");
//allows for toast to be displayed once button is clicked
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
toast.makeText(MainActivity.this, txtInput.getText() + " Has Been Shouted.", toast.LENGTH_SHORT).show();
}
here is my activity main xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#000000" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</android.support.v4.view.ViewPager>
viewpageradapter class
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] {"Home","Shouts","Shouts" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
public Fragment getItem(int position) {
switch (position) {
// Open Fragment home.java
case 0:
FragmentHome fragmenthome = new FragmentHome();
return fragmenthome;
// Open Fragment shouters.java
case 1:
FragmentShouts fragmentshouts = new FragmentShouts();
return fragmentshouts;
case 2:
FragmentShouts fragmentShouts = new FragmentShouts();
return fragmentShouts;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
here is my tab with the user input (home fragment class)
public class FragmentHome extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragment home.xml
View view = inflater.inflate(R.layout.fragmenthome, container, false);
return view;
}
here is fragment home xml
<RelativeLayout 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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="New Shout"
android:id="#+id/lblShout"
android:layout_marginBottom="134dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txtInput"
android:layout_alignTop="#+id/lblShout"
android:layout_alignParentStart="true"
android:layout_marginTop="41dp"
android:layout_alignParentEnd="true"
android:hint="Enter New Shout..." />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SHOUT"
android:id="#+id/button"
android:layout_below="#+id/txtInput"
android:layout_centerHorizontal="true"
android:onClick="btnShout" />
</RelativeLayout>
here is the fragment with the listview (shouts fragment class)
public class FragmentShouts extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragment shouts.xml
View view = inflater.inflate(R.layout.fragmentshouts, container, false);
return view;
}
here is the fragment shouts xml
<RelativeLayout 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"
android:clickable="true"
android:contextClickable="true">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I have a problem with the TabLayout in Android. I'm using AppCompat library because my min SDK is 10. The problem is that if the TabLayout has visibility GONE when the activity is first created, when I set the visibility to VISIBLE later, the tab tittles and tab indicator are missing.
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Called when we press the button.
*/
public void openTabActivity(View view) {
Intent intent = new Intent(this, TabActivity.class);
startActivity(intent);
}
}
TabActivity is this:
public class TabActivity extends FragmentActivity {
MyPagerAdapter mMyPagerAdapter;
ViewPager mViewPager;
TabLayout mTabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mMyPagerAdapter =
new MyPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.myViewPager);
mViewPager.setAdapter(mMyPagerAdapter);
// Link the TabLayout with the ViewPager.
mTabLayout = (TabLayout) findViewById(R.id.myTab);
mTabLayout.setupWithViewPager(mViewPager);
// If I set visibility GONE it doesn't show titles
// when I set it to VISIBLE again.
// If I remove this, it works fine.
mTabLayout.setVisibility(View.GONE);
}
/**
* If the tab is visible it turn it gone, if it's gone it turn it
* visible.
* #param view
*/
public void toggleTab(View view) {
Log.d(this.getClass().toString(), "ShowTab()");
if (mTabLayout.getVisibility() == View.VISIBLE) {
Log.d(this.getClass().toString(), "Turning GONE");
mTabLayout.setVisibility(View.GONE);
} else {
Log.d(this.getClass().toString(), "Turning VISIBLE");
mTabLayout.setVisibility(View.VISIBLE);
}
}
}
Page adapter:
public class MyPagerAdapter extends FragmentStatePagerAdapter {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab 1", "Tab 2", "Tab 3"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new MyFragment();
return fragment;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Fragment:
public class MyFragment extends Fragment {
public static MyFragment newInstance() {
MyFragment fragment = new MyFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
return view;
}
}
Layouts are very simple too:
activity_main.xml
<RelativeLayout 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="200dp"
android:onClick="openTabActivity"
android:textColor="#55F"
android:text="Press to go to Tabs"/>
</RelativeLayout>
activity_tab.xml
<LinearLayout 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"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".TabActivity">
<android.support.design.widget.TabLayout
android:id="#+id/myTab"
style="#style/AppTheme.Tab.NavigationTab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/lightPrimaryColor"/>
<android.support.v4.view.ViewPager
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"/>
</LinearLayout>
my_fragment.xml
<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=".MyFragment">
<Button
android:layout_width="200dp"
android:layout_height="200dp"
android:onClick="toggleTab"
android:text="Press"/>
</FrameLayout>
If i set visibility GONE in TabActivity.onCreate it fails. If it's VISIBLE in TabActivity.onCreate it works.
I've tried to use .invalidate() but it doesn't work.
Can anybody help me?
Thanks in advance for your help.
Confirmed. It's a bug in library com.android.support:design:22.2.1. If I use com.android.support:design:22.2.0 it works perfectly. It will be solved in future releases of the library.
Here is the issue in code.google.com
Not sure if its the same issue but something similar was happening to me when I didn't have tabTextColor and tabSelectedTextColor style attributes set.
Broke when upgraded to com.android.support:support-v13:23.1.1 from 22.2.0, solved with following style:
<style name="exploreTabLayout" parent="Widget.Design.TabLayout">
<item name="tabIndicatorColor">#color/accent_teal</item>
<item name="tabIndicatorHeight">4dp</item>
<item name="tabTextColor">#color/bismark_blue</item>
<item name="tabSelectedTextColor">#color/accent_teal</item>
</style>
I have been learning to use Sliding Tabs using Material Design using this post. I have managed to achieve SlidingTabs below the Toolbar, like this one:
But now i would like to create ActionBar/ToolBar Fragment Tabs ...
I was able to recreate exactly what you are looking to implement. I am using the this Library for the tabs.
This is the view I have created:
Import Library Through Dependencies or Download Project and Import Manually
compile 'com.jpardogo.materialtabstrip:library:1.0.9'
styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/primary</item>
<item name="colorPrimaryDark">#color/primary_dark</item>
</style>
</resources>
MainActivity & Adapter
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
ViewPager viewPager;
ContactPagerAdapter pagerAdapter;
PagerSlidingTabStrip pagerSlidingTabStrip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setLogo(R.mipmap.logo_two);
toolbar.inflateMenu(R.menu.menu_main);
viewPager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new ContactPagerAdapter(this, getSupportFragmentManager());
pagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
viewPager.setAdapter(pagerAdapter);
pagerSlidingTabStrip.setViewPager(viewPager);
}
public static class ContactPagerAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.CustomTabProvider {
private final int[] ICONS = {R.mipmap.ic_launcher, R.mipmap.ic_launcher};
Context mContext;
private Fragment f = null;
public ContactPagerAdapter(Context ctx, FragmentManager fm) {
super(fm);
mContext = ctx;
}
#Override
public int getCount() {
return ICONS.length;
}
#Override
public Fragment getItem(int position) { // Returns Fragment based on position
switch (position) {
case 0:
f = new FragmentPageOne();
break;
case 1:
f = new FragmentPageTwo();
break;
}
return f;
}
#Override
public View getCustomTabView(ViewGroup parent, int position) {
LinearLayout customLayout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.custom_tab, parent, false);
ImageView imageView = (ImageView) customLayout.findViewById(R.id.image);
imageView.setImageResource(ICONS[position]);
return customLayout;
}
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#02a6d8"
android:minHeight="56dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="wrap_content"
android:layout_height="56dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp"
android:background="#02a6d8"
app:pstsDividerColor="#02a6d8"
app:pstsIndicatorColor="#fff"
app:pstsIndicatorHeight="2dp"
app:pstsShouldExpand="false"
app:pstsUnderlineHeight="0dp"/>
</android.support.v7.widget.Toolbar>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"/>
<!-- Shadow below toolbar-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#+id/toolbar"
android:background="#drawable/toolbar_shadow"/>
</RelativeLayout>
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="30dp"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingBottom="8dp"
android:paddingTop="8dp"/>
</LinearLayout>
Drawrable toolbar_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="270"
android:endColor="#android:color/transparent"
android:startColor="#color/semi_transparent"/>
</shape>
In fact the tabs are not in the toolbar. The toolbar is just hidden. You can hide the toolbar calling getSupportActionBar().hide() and the toolbar will be gone. As a result of this the tabs will be at the top of the screen.
As i already wrote you can find an example here: http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html
By the way, what you need to is include in your project this code: https://developer.android.com/samples/SlidingTabsColors/src/com.example.android.common/view/SlidingTabLayout.html. So create a class in which you will paste the entire code.
Then create your activity that extends ActionBarActivity like for example this one:
public class MainActivity extends ActionBarActivity {
static final String LOG_TAG = "SlidingTabsBasicFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_sample);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new SamplePagerAdapter());
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
/*
* FragmentTransaction transaction =
* getSupportFragmentManager().beginTransaction();
* SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
* transaction.replace(R.id.sample_content_fragment, fragment);
* transaction.commit();
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SamplePagerAdapter extends PagerAdapter {
/**
* #return the number of pages to display
*/
#Override
public int getCount() {
return 5;
}
/**
* #return true if the value returned from
* {#link #instantiateItem(ViewGroup, int)} is the same object
* as the {#link View} added to the {#link ViewPager}.
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
// BEGIN_INCLUDE (pageradapter_getpagetitle)
/**
* Return the title of the item at {#code position}. This is important
* as what this method returns is what is displayed in the
* {#link SlidingTabLayout}.
* <p>
* Here we construct one using the position value, but for real
* application the title should refer to the item's contents.
*/
#Override
public CharSequence getPageTitle(int position) {
return "Item " + (position + 1);
}
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at
* {#code position}. Here we inflate a layout from the apps resources
* and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = getLayoutInflater().inflate(R.layout.pager_item,
container, false);
// Add the newly created View to the ViewPager
container.addView(view);
// Retrieve a TextView from the inflated View, and update it's text
TextView title = (TextView) view.findViewById(R.id.item_title);
title.setText(String.valueOf(position + 1));
Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");
// Return the View
return view;
}
/**
* Destroy the item from the {#link ViewPager}. In our case this is
* simply removing the {#link View}.
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
}
}
of course this fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/my_awesome_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.example.android.common.view.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
and the pager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/item_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Page:"/>
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="80sp" />
</LinearLayout>
This is the way to do it.
You can also use this library: https://github.com/florent37/MaterialViewPager or this one: https://android-arsenal.com/details/1/1100
I am learning how to use navigation drawer and navigation tab. I created an app that implement a navigation drawer on MainActivity and each item on navigation drawer will replace fragment on MainActivity to the corresponding fragment.
My first fragment provide two navigation tab using SlidingTabLayout and SlidingTabStrip. The other fragments are just a textview.
If I move from the first item to the second item and then back to first item again, my tab still show two tab, but in fact, I can slide more than two times and the content is not shown.
How do I fix this?
What it should be:
After I move to second drawer and then back to first drawer:
What happened after that:
You can see that I can slide more than twice and the content of fragments are not shown.
MainActivity.java
public class MainActivity extends ActionBarActivity {
String titles[] = {"TabsFragment", "TextFragment"};
Fragment fragment[] = {TabsFragment.newInstance(), TextFragment.newInstance()};
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
DrawerLayout drawer;
ActionBarDrawerToggle mDrawerToggle;
static View.OnClickListener drawerItemClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
mRecyclerView.setHasFixedSize(true);
mAdapter = new DrawerAdapter(titles);
drawerItemClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedPos = mRecyclerView.getChildPosition(v);
drawer.closeDrawers();
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_content, fragment[selectedPos])
.commit();
}
};
mRecyclerView.setAdapter(mAdapter);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
drawer,
toolbar,
R.string.open_drawer,
R.string.close_drawer) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
supportInvalidateOptionsMenu();
}
};
drawer.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_content, fragment[0])
.commit();
}
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize" />
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.DrawerLayout>
TabsFragment.java
public class TabsFragment extends Fragment {
public static Fragment newInstance() {
TabsFragment fragment = new TabsFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tabs, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new SamplePagerAdapter(getActivity().getSupportFragmentManager(), getActivity().getApplicationContext()));
SlidingTabLayout mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setDistributeEvenly(true);
mSlidingTabLayout.setViewPager(mViewPager);
}
class SamplePagerAdapter extends FragmentPagerAdapter {
private String[] tabTitles = new String[] {"Tab One", "Tab Two"};
private Context context;
public SamplePagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment[] fragment = {TabOneFragment.newInstance(), TabTwoFragment.newInstance()};
return fragment[position];
}
}
}
fragment_tabs.xml
<RelativeLayout
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=".TabsFragment">
<android.com.drawertab.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/sliding_tabs" />
</RelativeLayout>
TabsOneFragment.java
public class TabOneFragment extends Fragment{
public static TabOneFragment newInstance() {
TabOneFragment fragment = new TabOneFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab_one, container, false);
}
}
fragment_tabs_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:id="#+id/text"
android:text="TAB ONE" />
</LinearLayout>
TabsTwoFragment.java
public class TabTwoFragment extends Fragment {
public static TabTwoFragment newInstance() {
TabTwoFragment fragment = new TabTwoFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab_two, container, false);
}
}
fragment_tabs_two.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:id="#+id/text"
android:text="TAB TWO" />
</LinearLayout>
TextFragment.java
public class TextFragment extends Fragment {
public static Fragment newInstance() {
TextFragment fragment = new TextFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_text, container, false);
}
}
fragment_text.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:id="#+id/text"
android:text="FRAGMENT TEXT" />
</LinearLayout>
DrawerAdapter.java
public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder> {
private String mNavTitles[];
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView,int ViewType) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.rowText);
itemView.setOnClickListener(MainActivity.drawerItemClickListener);
}
}
public DrawerAdapter(String[] titles) {
mNavTitles = titles;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_item_row, parent, false);
ViewHolder vhItem = new ViewHolder(v, viewType);
return vhItem;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(mNavTitles[position]);
}
#Override
public int getItemCount() {
return mNavTitles.length;
}
}
drawer_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="12dp"
android:paddingTop="4dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/rowText" />
</LinearLayout>
If you are correct about sliding more times than twice, then you need to set the override method getCount correctly (I realize you know). That's the only issue you need to worry about.
private String[] tabTitles = new String[] {"Tab One", "Tab Two"};
...
#Override
public int getCount() {
return tabTitles.length;
}
Note: I declared tabTitles differently as an array of String "String[]", widely accepted. The other style "tabTitles[]" may not work well with its methods like length.
Looking at your code more closely, I suspect objects TabOneFragment and TabTwoFragment is not working well. Normally override getItem returns the same static Fragment. And of course, I do not see that declaration or code for it.
My suggested try is (from your code):
#Override
public android.support.v4.app.Fragment getItem(int position) {
return TabsFragment.newInstance(position);
}
Note: With the above code, I don't see any use for TabOneFragment and TabTwoFragment, referenced in getItem(int position) in SamplePagerAdapter class. The TextView UI in layout fragment_tab_one.xml is only used for the tab texts. For those texts, the override getPageTitle(int position) can be used and is already coded.