TabLayout text disappears when visibility goes from GONE to VISIBLE - android

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>

Related

Setonitemclicklistener inside fragment of tabbed activity

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.

How to implement the avatar selection screen like this in android without using any library?

this is my first question here. I am trying implement similar avatar selection screen for my college project. I searched almost everywhere and it seems like it can be done using viewpager. I tried but cant achieve similar effect. I have problem is showing all child in at the same time. and also i cant able to achieve the select avatar scaled in high and rest in low. Please help me out, i want to implement quickly as possible without using any library because i want to understand how it can be implemented without it as of now. Thanks in advance.
I have tried to create a viewpager with 3 images. This is my implementation.
MainActivity.java with MyPagerAdapter
public class MainActivity extends AppCompatActivity {
FragmentPagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstFragment.newInstance(R.drawable.a);
case 1:
return SecondFragment.newInstance(R.drawable.b);
case 2:
return ThirdFragment.newInstance(R.drawable.c);
default:
return null;
}
}
#Override
public int getCount() {
return NUM_ITEMS;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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">
<android.support.v4.view.ViewPager
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
</RelativeLayout>
I have 3 Fragements. This is one of the fragement.
FirstFragment.java
public class FirstFragment extends Fragment {
private int image;
public FirstFragment() {
}
public static FirstFragment newInstance(int resImage) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt("image", resImage);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
image = getArguments().getInt("image", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.firstImg);
imageView.setImageResource(image);
return view;
}
}
This is fragment_first.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:id="#+id/firstImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>

Replace fragment in fragment itself in TabActivity

I am sorry on the duplicate question but I didn't get answer for my problem.
I create app with TabActivity and also trying to replace one fragment from fragment itself, I read in https://developer.android.com/training/basics/fragments/fragment-ui.html how to do it and i created interface in my fragment that i want to be replace with another,
I implement the interface in my MainActivity and still when running my app it show me container itself.
here is my code:
Main Activity:
public class MainActivity extends FragmentActivity implements New2.OnReplaceFragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static MainActivity instance = null;
public static MainActivity getInstance(){
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
instance = this;
}
#Override
public void onReplaceFragment(Class fragmentClass) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container,fragment);
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
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() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
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:
// New1 tab1 = new New1();
return New1.newInstance();
case 1:
return New2.newInstance();
case 2:
return New3.newInstance();
default:
return null;
}
}
#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;
}
}
}
my fragment that I want to replace
Fragment:
public class New2 extends Fragment {
TextView name;
Button change;
ImageView image1;
Animation anime;
private OnReplaceFragment dataPasser;
public static New2 newInstance(){
New2 fragment = new New2();
return fragment;
}
public New2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new2, container, false);
name = (TextView) rootView.findViewById(R.id.nameTt);
change = (Button) rootView.findViewById(R.id.changeBtn);
image1 = (ImageView) rootView.findViewById(R.id.image1);
anime = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.zoom);
change.setOnClickListener(changeName);
return rootView;
}
View.OnClickListener changeName = new View.OnClickListener() {
#Override
public void onClick(View view) {
image1.startAnimation(anime);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run(){
dataPasser.onReplaceFragment(Result.class);
}
},1000);
}
};
public interface OnReplaceFragment {
public void onReplaceFragment(Class fragmentClass);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
dataPasser = (OnReplaceFragment) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString() + " must implement onDataPass");
}
}
}
the fragment that i want to display
public class Result extends Fragment {
TextView textView;
Button btnBack;
public static Result instance = null;
public static Result getInstance(){
return instance;
}
public Result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_result, container, false);
textView = (TextView) v.findViewById(R.id.text11);
btnBack = (Button) v.findViewById(R.id.btnBack);
textView.setText("working!!");
Toast.makeText(getActivity().getApplicationContext(),"working",Toast.LENGTH_LONG).show();
return v;
}
}
Main Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<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.example.hercules.tadhosttutrial.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:background="#color/red"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
New2 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="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/changeBtn"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:text="change"/>
<ImageView
android:id="#+id/image1"
android:background="#drawable/icon_complete"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
Result 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:background="#color/colorAccent"
tools:context="com.example.hercules.tadhosttutrial.Result">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"/>
<TextView
android:id="#+id/text11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WORKING"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="70dp"
/>
</RelativeLayout>
What i mean, is making MainActivity as a main container for all fragments, either with tabs or just a regular fragment,
1- Main Activity XML: remove ViewPager, add a FrameLayout instead (use same id)
2- Create new fragment TabsFragment with this 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="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
3- Move initializing SectionsPagerAdapter and ViewPager from main activity to TabsFragment:
this part:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
and this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
4- I think moving SectionsPagerAdapter class in a new file is better too.
now if you want default view for app to be the tabs, then in MainActivity at onCreate() show TabsFragment by calling your method:
onReplaceFragment(TabsFragment.class);
now every thing should work fine, because the idea here is to replace the fragment displayed in main activity with another one
in this case TabsFragment, Result, and New2
not to replace viewpager fragments (because as i told you this is managed via the adapter) not by calling replace()
you may need to play around this, it's not a final code, just something to give you idea about it.

Android TabLayout Android Design

I'm trying to get the new TabLayout in the android design library working.
I'm following this post:
http://android-developers.blogspot.com/2015/05/android-design-support-library.html
and the documentation:
http://developer.android.com/reference/android/support/design/widget/TabLayout.html
And have come up with the following code in my activity but the tablayout isn't showing up when I run the activity.
I tried adding in the activity layout file, but it says it can't find that xml tag.
public class TabActivity extends BaseActivity {
SectionPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
LinearLayout v = (LinearLayout)findViewById(R.id.tabContainer);
TabLayout tabLayout = new TabLayout(this);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setLayoutParams(new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 50));
v.addView(tabLayout);
mSectionsPagerAdapter = new SectionPagerAdapter(getFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
private String TAG = "SectionPagerAdapter";
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
return new Fragment();
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "test";
case 1:
return "test";
case 2:
}
return null;
}
}
}
Added the following to my gradle file
compile 'com.android.support:design:22.2.0'
I've just managed to setup new TabLayout, so here are the quick steps to do this (ノ◕ヮ◕)ノ*:・゚✧
Add dependencies inside your build.gradle file:
dependencies {
compile 'com.android.support:design:23.1.1'
}
Add TabLayout inside your 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
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Setup your Activity like this:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class TabLayoutActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstTabFragment();
case 1:
default:
return new SecondTabFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
default:
return "Second Tab";
}
}
}
}
I had to collect information from various sources to put together a functioning TabLayout. The following is presented as a complete use case that can be modified as needed.
Make sure the module build.gradle file contains a dependency on com.android.support:design.
dependencies {
compile 'com.android.support:design:23.1.1'
}
In my case, I am creating an About activity in the application with a TabLayout. I added the following section to AndroidMainifest.xml. Setting the parentActivityName allows the home arrow to take the user back to the main activity.
<!-- android:configChanges="orientation|screenSize" makes the activity not reload when the orientation changes. -->
<activity
android:name=".AboutActivity"
android:label="#string/about_app"
android:theme="#style/MyApp.About"
android:parentActivityName=".MainActivity"
android:configChanges="orientation|screenSize" >
<!-- android.support.PARENT_ACTIVITY is necessary for API <= 15. -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
styles.xml contains the following entries. This app has a white AppBar for the main activity and a blue AppBar for the About activity. We need to set colorPrimaryDark for the About activity so that the status bar above the AppBar is blue.
<style name="MyApp" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorAccent">#color/blue</item>
</style>
<style name="MyApp.About" />
<!-- ThemeOverlay.AppCompat.Dark.ActionBar" makes the text and the icons in the AppBar white. -->
<style name="MyApp.DarkAppBar" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="MyApp.AppBarOverlay" parent="ThemeOverlay.AppCompat.ActionBar" />
<style name="MyApp.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
There is also a styles.xml (v19). It is located at src/main/res/values-v19/styles.xml. This file is only applied if the API of the device is >= 19.
<!-- android:windowTranslucentStatus requires API >= 19. It makes the system status bar transparent.
When it is specified the root layout should include android:fitsSystemWindows="true".
colorPrimaryDark goes behind the status bar, which is then darkened by the overlay. -->
<style name="MyApp.About">
<item name="android:windowTranslucentStatus">true</item>
<item name="colorPrimaryDark">#color/blue</item>
</style>
AboutActivity.java contains the following code. In my case I have a fixed number of tabs (7) so I could remove all the code dealing with dynamic tabs.
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class AboutActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_coordinatorlayout);
// We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
Toolbar supportAppBar = (Toolbar) findViewById(R.id.about_toolbar);
setSupportActionBar(supportAppBar);
// Display the home arrow on supportAppBar.
final ActionBar appBar = getSupportActionBar();
assert appBar != null;// This assert removes the incorrect warning in Android Studio on the following line that appBar might be null.
appBar.setDisplayHomeAsUpEnabled(true);
// Setup the ViewPager.
ViewPager aboutViewPager = (ViewPager) findViewById(R.id.about_viewpager);
assert aboutViewPager != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutViewPager might be null.
aboutViewPager.setAdapter(new aboutPagerAdapter(getSupportFragmentManager()));
// Setup the TabLayout and connect it to the ViewPager.
TabLayout aboutTabLayout = (TabLayout) findViewById(R.id.about_tablayout);
assert aboutTabLayout != null; // This assert removes the incorrect warning in Android Studio on the following line that aboutTabLayout might be null.
aboutTabLayout.setupWithViewPager(aboutViewPager);
}
public class aboutPagerAdapter extends FragmentPagerAdapter {
public aboutPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
// Get the count of the number of tabs.
public int getCount() {
return 7;
}
#Override
// Get the name of each tab. Tab numbers start at 0.
public CharSequence getPageTitle(int tab) {
switch (tab) {
case 0:
return getString(R.string.version);
case 1:
return getString(R.string.permissions);
case 2:
return getString(R.string.privacy_policy);
case 3:
return getString(R.string.changelog);
case 4:
return getString(R.string.license);
case 5:
return getString(R.string.contributors);
case 6:
return getString(R.string.links);
default:
return "";
}
}
#Override
// Setup each tab.
public Fragment getItem(int tab) {
return AboutTabFragment.createTab(tab);
}
}
}
AboutTabFragment.java is used to populate each tab. In my case, the first tab has a LinearLayout inside of a ScrollView and all the others have a WebView as the root layout.
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.TextView;
public class AboutTabFragment extends Fragment {
private int tabNumber;
// AboutTabFragment.createTab stores the tab number in the bundle arguments so it can be referenced from onCreate().
public static AboutTabFragment createTab(int tab) {
Bundle thisTabArguments = new Bundle();
thisTabArguments.putInt("Tab", tab);
AboutTabFragment thisTab = new AboutTabFragment();
thisTab.setArguments(thisTabArguments);
return thisTab;
}
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Store the tab number in tabNumber.
tabNumber = getArguments().getInt("Tab");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View tabLayout;
// Load the about tab layout. Tab numbers start at 0.
if (tabNumber == 0) {
// Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
// The fragment will take care of attaching the root automatically.
tabLayout = inflater.inflate(R.layout.about_tab_version, container, false);
} else { // load a WebView for all the other tabs. Tab numbers start at 0.
// Setting false at the end of inflater.inflate does not attach the inflated layout as a child of container.
// The fragment will take care of attaching the root automatically.
tabLayout = inflater.inflate(R.layout.about_tab_webview, container, false);
WebView tabWebView = (WebView) tabLayout;
switch (tabNumber) {
case 1:
tabWebView.loadUrl("file:///android_asset/about_permissions.html");
break;
case 2:
tabWebView.loadUrl("file:///android_asset/about_privacy_policy.html");
break;
case 3:
tabWebView.loadUrl("file:///android_asset/about_changelog.html");
break;
case 4:
tabWebView.loadUrl("file:///android_asset/about_license.html");
break;
case 5:
tabWebView.loadUrl("file:///android_asset/about_contributors.html");
break;
case 6:
tabWebView.loadUrl("file:///android_asset/about_links.html");
break;
default:
break;
}
}
return tabLayout;
}
}
about_coordinatorlayout.xml is as follows:
<!-- android:fitsSystemWindows="true" moves the AppBar below the status bar.
When it is specified the theme should include <item name="android:windowTranslucentStatus">true</item>
to make the status bar a transparent, darkened overlay. -->
<android.support.design.widget.CoordinatorLayout
android:id="#+id/about_coordinatorlayout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true" >
<!-- the LinearLayout with orientation="vertical" moves the ViewPager below the AppBarLayout. -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- We need to set android:background="#color/blue" here or any space to the right of the TabLayout on large devices will be white. -->
<android.support.design.widget.AppBarLayout
android:id="#+id/about_appbarlayout"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="#color/blue"
android:theme="#style/MyApp.AppBarOverlay" >
<!-- android:theme="#style/PrivacyBrowser.DarkAppBar" makes the text and icons in the AppBar white. -->
<android.support.v7.widget.Toolbar
android:id="#+id/about_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
android:theme="#style/MyApp.DarkAppBar"
app:popupTheme="#style/MyApp.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/about_tablayout"
xmlns:android.support.design="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android.support.design:tabBackground="#color/blue"
android.support.design:tabTextColor="#color/light_blue"
android.support.design:tabSelectedTextColor="#color/white"
android.support.design:tabIndicatorColor="#color/white"
android.support.design:tabMode="scrollable" />
</android.support.design.widget.AppBarLayout>
<!-- android:layout_weight="1" makes about_viewpager fill the rest of the screen. -->
<android.support.v4.view.ViewPager
android:id="#+id/about_viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
about_tab_version.xml is as follows:
<!-- The ScrollView allows the LinearLayout to scroll if it exceeds the height of the page. -->
<ScrollView
android:id="#+id/about_version_scrollview"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent" >
<LinearLayout
android:id="#+id/about_version_linearlayout"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:padding="16dp" >
<!-- Include whatever content you want in this tab here. -->
</LinearLayout>
</ScrollView>
And about_tab_webview.xml:
<!-- This WebView displays inside of the tabs in AboutActivity. -->
<WebView
android:id="#+id/about_tab_webview"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" />
There are also entries in strings.xml
<string name="about_app">About App</string>
<string name="version">Version</string>
<string name="permissions">Permissions</string>
<string name="privacy_policy">Privacy Policy</string>
<string name="changelog">Changelog</string>
<string name="license">License</string>
<string name="contributors">Contributors</string>
<string name="links">Links</string>
And colors.xml
<color name="blue">#FF1976D2</color>
<color name="light_blue">#FFBBDEFB</color>
<color name="white">#FFFFFFFF</color>
src/main/assets contains the HTML files referenced in AboutTabFragemnt.java.
I try to solve here is my code.
first add dependency in build.gradle(app).
dependencies {
compile 'com.android.support:design:23.1.1'
}
Create PagerAdapter.class
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Log.i("PosTabItem",""+position);
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
Log.i("PosTab",""+position);
return mFragmentTitleList.get(position);
}
}
create activity_main.xml
<RelativeLayout 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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout" />
</RelativeLayout>
create MainActivity.class
public class MainActivity extends AppCompatActivity {
Pager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
pager = new Pager(getSupportFragmentManager());
pager.addFragment(new FragmentOne(), "One");
viewPager.setAdapter(pager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setSmoothScrollingEnabled(true);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
and finally create fragment to add in viewpager
crate fragment_one.xml
<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:text="Location"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Create FragmentOne.class
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container,false);
return view;
}
}
I am facing some issue with menu change when fragment changes in ViewPager. I ended up implemented below code.
DashboardFragment
public class DashboardFragment extends BaseFragment {
private Context mContext;
private TabLayout mTabLayout;
private ViewPager mViewPager;
private DashboardPagerAdapter mAdapter;
private OnModuleChangeListener onModuleChangeListener;
private NavDashBoardActivity activityInstance;
public void setOnModuleChangeListener(OnModuleChangeListener onModuleChangeListener) {
this.onModuleChangeListener = onModuleChangeListener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dashboard_fragment, container, false);
}
//pass -1 if you want to get it via pager
public Fragment getFragmentFromViewpager(int position) {
if (position == -1)
position = mViewPager.getCurrentItem();
return ((Fragment) (mAdapter.instantiateItem(mViewPager, position)));
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContext = getActivity();
activityInstance = (NavDashBoardActivity) getActivity();
mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
final List<EnumUtils.Module> moduleToShow = getModuleToShowList();
mViewPager.setOffscreenPageLimit(moduleToShow.size());
for(EnumUtils.Module module :moduleToShow)
mTabLayout.addTab(mTabLayout.newTab().setText(EnumUtils.Module.getTabText(module)));
updateTabPagerAndMenu(0 , moduleToShow);
mAdapter = new DashboardPagerAdapter(getFragmentManager(),moduleToShow);
mViewPager.setOffscreenPageLimit(mAdapter.getCount());
mViewPager.setAdapter(mAdapter);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(final TabLayout.Tab tab) {
mViewPager.post(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//added to redraw menu on scroll
}
#Override
public void onPageSelected(int position) {
updateTabPagerAndMenu(position , moduleToShow);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
//also validate other checks and this method should be in SharedPrefs...
public static List<EnumUtils.Module> getModuleToShowList(){
List<EnumUtils.Module> moduleToShow = new ArrayList<>();
moduleToShow.add(EnumUtils.Module.HOME);
moduleToShow.add(EnumUtils.Module.ABOUT);
return moduleToShow;
}
public void setCurrentTab(final int position){
if(mViewPager != null){
mViewPager.postDelayed(new Runnable() {
#Override
public void run() {
mViewPager.setCurrentItem(position);
}
},100);
}
}
private Fragment getCurrentFragment(){
return mAdapter.getCurrentFragment();
}
private void updateTabPagerAndMenu(int position , List<EnumUtils.Module> moduleToShow){
//it helps to change menu on scroll
//http://stackoverflow.com/a/27984263/3496570
//No effect after changing below statement
ActivityCompat.invalidateOptionsMenu(getActivity());
if(mTabLayout != null)
mTabLayout.getTabAt(position).select();
if(onModuleChangeListener != null){
if(activityInstance != null){
activityInstance.updateStatusBarColor(
EnumUtils.Module.getStatusBarColor(moduleToShow.get(position)));
}
onModuleChangeListener.onModuleChanged(moduleToShow.get(position));
mTabLayout.setSelectedTabIndicatorColor(EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
mTabLayout.setTabTextColors(ContextCompat.getColor(mContext,android.R.color.black)
, EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
}
}
}
dashboardfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabBackground="#android:color/white"
app:tabGravity="fill"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/black"
app:tabTextColor="#android:color/black" />
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
DashboardPagerAdapter
public class DashboardPagerAdapter extends FragmentPagerAdapter {
private List<EnumUtils.Module> moduleList;
private Fragment mCurrentFragment = null;
public DashboardPagerAdapter(FragmentManager fm, List<EnumUtils.Module> moduleList){
super(fm);
this.moduleList = moduleList;
}
#Override
public Fragment getItem(int position) {
return EnumUtils.Module.getDashboardFragment(moduleList.get(position));
}
#Override
public int getCount() {
return moduleList.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
public int getModulePosition(EnumUtils.Module moduleName){
for(int x = 0 ; x < moduleList.size() ; x++){
if(moduleList.get(x).equals(moduleName))
return x;
}
return -1;
}
}
And in each page of Fragment setHasOptionMenu(true) in onCreate and implement onCreateOptionMenu. then it will work properly.
dASHaCTIVITY
public class NavDashBoardActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Context mContext;
private DashboardFragment dashboardFragment;
private Toolbar mToolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_dash_board);
mContext = NavDashBoardActivity.this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color.yellow_action_bar));
}
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
updateToolbarText(new ToolbarTextBO("NCompass " ,""));
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//onclick of back button on Navigation it will popUp fragment...
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!toggle.isDrawerIndicatorEnabled()) {
getSupportFragmentManager().popBackStack();
}
}
});
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);//It helps to show icon on Navigation
updateNavigationMenuItem(navigationView);
navigationView.setNavigationItemSelectedListener(this);
//Left Drawer Upper Section
View headerLayout = navigationView.getHeaderView(0); // 0-index header
TextView userNameTv = (TextView) headerLayout.findViewById(R.id.tv_user_name);
userNameTv.setText(AuthSharePref.readUserLoggedIn().getFullName());
RoundedImageView ivUserPic = (RoundedImageView) headerLayout.findViewById(R.id.iv_user_pic);
ivUserPic.setImageResource(R.drawable.profile_img);
headerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//close drawer and add a fragment to it
drawer.closeDrawers();//also try other methods..
}
});
//ZA code starts...
dashboardFragment = new DashboardFragment();
dashboardFragment.setOnModuleChangeListener(new OnModuleChangeListener() {
#Override
public void onModuleChanged(EnumUtils.Module module) {
if(mToolbar != null){
mToolbar.setBackgroundColor(EnumUtils.Module.getModuleColor(module));
if(EnumUtils.Module.getMenuID(module) != -1)
navigationView.getMenu().findItem(EnumUtils.Module.getMenuID(module)).setChecked(true);
}
}
});
addBaseFragment(dashboardFragment);
backStackListener();
}
public void updateStatusBarColor(int colorResourceID){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(colorResourceID);
}
}
private void updateNavigationMenuItem(NavigationView navigationView){
List<EnumUtils.Module> modules = DashboardFragment.getModuleToShowList();
if(!modules.contains(EnumUtils.Module.MyStores)){
navigationView.getMenu().findItem(R.id.nav_my_store).setVisible(false);
}
if(!modules.contains(EnumUtils.Module.Livewall)){
navigationView.getMenu().findItem(R.id.nav_live_wall).setVisible(false);
}
}
private void backStackListener(){
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
{
toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); //set your own
///toggle.setDrawerArrowDrawable();
///toggle.setDrawerIndicatorEnabled(false); // this will hide hamburger image
///Toast.makeText(mContext,"Update to Arrow",Toast.LENGTH_SHORT).show();
}
else{
toggle.setDrawerIndicatorEnabled(true);
}
if(getSupportFragmentManager().getBackStackEntryCount() >0){
if(getCurrentFragment() instanceof DashboardFragment){
Fragment subFragment = ((DashboardFragment) getCurrentFragment())
.getViewpager(-1);
}
}
else{
}
}
});
}
private void updateToolBarTitle(String title){
getSupportActionBar().setTitle(title);
}
public void updateToolBarColor(String hexColor){
if(mToolbar != null)
mToolbar.setBackgroundColor(Color.parseColor(hexColor));
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (drawer.isDrawerOpen(GravityCompat.START))
getMenuInflater().inflate(R.menu.empty, menu);
return super.onCreateOptionsMenu(menu);//true is wriiten first..
}
#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 == android.R.id.home)
{
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
} else
drawer.openDrawer(GravityCompat.START);
}
return false;///true;
}
return false;// false so that fragment can also handle the menu event. Otherwise it is handled their
///return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_my_store) {
// Handle the camera action
dashboardFragment.setCurrentTab(EnumUtils.Module.MyStores);
}
}else if (id == R.id.nav_log_out) {
Dialogs.logOut(mContext);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void updateToolbarText(ToolbarTextBO toolbarTextBO){
mToolbar.setTitle("");
mToolbar.setSubtitle("");
if(toolbarTextBO.getTitle() != null && !toolbarTextBO.getTitle().isEmpty())
mToolbar.setTitle(toolbarTextBO.getTitle());
if(toolbarTextBO.getDescription() != null && !toolbarTextBO.getDescription().isEmpty())
mToolbar.setSubtitle(toolbarTextBO.getDescription());*/
}
#Override
public void onPostCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".ui.MainActivity"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
>
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
<android.support.design.widget.TabItem
android:id="#+id/tItemab4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_4" />
</android.support.design.widget.TabLayout>
</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_below="#id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:ignore="NotSibling"/>
</android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity">
<include layout="#layout/tabs"></include>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_marginTop="80dp">
<FrameLayout android:id="#+id/tabContent"
android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">
</FrameLayout>
</LinearLayout>
</RelativeLayout>
public class MainActivity extends AppCompatActivity{
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPagerAdapter adapter;
private final static int[] tabIcons = {
R.drawable.ic_action_car,
android.R.drawable.ic_menu_mapmode,
android.R.drawable.ic_dialog_email,
R.drawable.ic_action_settings
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new CarFragment());
adapter.addFrag(new LocationFragment());
adapter.addFrag(new MessageFragment());
adapter.addFrag(new SettingsFragment());
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFrag(Fragment fragment) {
mFragmentList.add(fragment);
}
}
}
So easy way :
XML:
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Java code:
private ViewPager viewPager;
private String[] PAGE_TITLES = new String[]{
"text1",
"text1",
"text3"
};
private final Fragment[] PAGES = new Fragment[]{
new fragment1(),
new fragment2(),
new fragment3()
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_a_requests);
/**TODO ***************tebLayout*************************/
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
tabLayout.setSelectedTabIndicatorHeight((int) (4 *
getResources().getDisplayMetrics().density));
tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"),
Color.parseColor("#0d0e10"));
tabLayout.setupWithViewPager(viewPager);
/***************************************************************************/
}
Add this to the module build.gradle:
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'

Why do I can slide to more than two times while I have only two tabs on Android?

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.

Categories

Resources