Android, Open activity from Specific TabBar item - java

I have a Tab Bar with 5 items 4 of these opens a new fragment while 1 of them should open a new activity, I can't figure out how to open this new activity.
I need the 3rd item to open a new activity(case 2).
I appreciate any help in this issue. Thank you.
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setTitle("");
toolbar.setSubtitle("");
// 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);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Frag1();
break;
case 1:
fragment = new Frag2();
break;
case 2:
fragment = new Frag3();
break;
case 3:
fragment = new Frag4();
break;
case 4:
fragment = new Frag5();
break;
}
return fragment;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
public static Bitmap TrimBitmap(Bitmap bmp) {
int imgHeight = bmp.getHeight();
int imgWidth = bmp.getWidth();
//TRIM WIDTH - LEFT
int startWidth = 0;
for(int x = 0; x < imgWidth; x++) {
if (startWidth == 0) {
for (int y = 0; y < imgHeight; y++) {
if (bmp.getPixel(x, y) != Color.TRANSPARENT) {
startWidth = x;
break;
}
}
} else break;
}
//TRIM WIDTH - RIGHT
int endWidth = 0;
for(int x = imgWidth - 1; x >= 0; x--) {
if (endWidth == 0) {
for (int y = 0; y < imgHeight; y++) {
if (bmp.getPixel(x, y) != Color.TRANSPARENT) {
endWidth = x;
break;
}
}
} else break;
}
//TRIM HEIGHT - TOP
int startHeight = 0;
for(int y = 0; y < imgHeight; y++) {
if (startHeight == 0) {
for (int x = 0; x < imgWidth; x++) {
if (bmp.getPixel(x, y) != Color.TRANSPARENT) {
startHeight = y;
break;
}
}
} else break;
}
//TRIM HEIGHT - BOTTOM
int endHeight = 0;
for(int y = imgHeight - 1; y >= 0; y--) {
if (endHeight == 0 ) {
for (int x = 0; x < imgWidth; x++) {
if (bmp.getPixel(x, y) != Color.TRANSPARENT) {
endHeight = y;
break;
}
}
} else break;
}
return Bitmap.createBitmap(
bmp,
startWidth,
startHeight,
endWidth - startWidth,
endHeight - startHeight
);
}
}
xml for tabbar(not sure if needed):
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/colorPrimaryDark"
app:tabGravity="fill"
app:tabIndicatorColor="#color/colorAccent"
app:tabMode="fixed"
app:tabSelectedTextColor="#android:color/background_light"
app:tabTextAppearance="#style/TabLayoutStyle"
app:tabTextColor="#android:color/background_light"
>
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5" />
</android.support.design.widget.TabLayout>

Use your own OnTabSelectedListener:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 2) { // 3rd item selected
// Open your activity here
}
}
void onTabUnselected(TabLayout.Tab tab) {}
void onTabReselected(TabLayout.Tab tab) {}
});

check for the tab item which you want(I am assuming you want to open the activity on case 2 if I am right, if not please change the code accordingly):
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Frag1();
break;
case 1:
fragment = new Frag2();
break;
case 2:
//open new activity
startActivity(new Intent(CurrentClassName.this, OtherClassName.class));
break;
case 3:
fragment = new Frag4();
break;
case 4:
fragment = new Frag5();
break;
}
return fragment;
}
Please be sure to change the CurrentClassName to what is the TabLayout activity's class name and OtherClassName to the class which you want to open!

Related

how to add image for headers in navigationdrawer in android

Hi in the below code in my project contains navigation drawer with expandable listview.
but everything was working fine. but want to display image for headers on leftside and arrow icon should be in right side for each header.
using json am parsing the data and in the same way want to display images for headers.
can any one help me how to do that one.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
ArrayList<Model_country> al_main = new ArrayList<>();
ExpandableListView ev_list;
CountryAdapter obj_adapter;
String TAG = "MainActivity";
private DrawerLayout mDrawerLayout;
HomeFragment fragment;
TextView tv_name;
RelativeLayout rl_menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fn_data();
init();
}
private void init() {
getSupportActionBar().hide();
ev_list = (ExpandableListView) findViewById(R.id.ev_menu);
tv_name = (TextView) findViewById(R.id.tv_name);
rl_menu = (RelativeLayout) findViewById(R.id.rl_menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
obj_adapter = new CountryAdapter(MainActivity.this, al_main);
ev_list.setAdapter(obj_adapter);
ev_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
setListViewHeight(parent, groupPosition);
return false;
}
});
setExpandableListViewHeightBasedOnChildren(ev_list);
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("name", al_main.get(0).getStr_country());
bundle.putString("des", al_main.get(0).getAl_state().get(0).getStr_description());
bundle.putString("dish", al_main.get(0).getAl_state().get(0).getStr_name());
bundle.putString("image", al_main.get(0).getAl_state().get(0).getStr_image());
tv_name.setText(al_main.get(0).getStr_country());
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();
rl_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
}
private void setListViewHeight(ExpandableListView listView, int group) {
ExpandableListAdapter listAdapter = (ExpandableListAdapter) listView.getExpandableListAdapter();
int totalHeight = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
View.MeasureSpec.EXACTLY);
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
View groupItem = listAdapter.getGroupView(i, false, null, listView);
groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (((listView.isGroupExpanded(i)) && (i != group))
|| ((!listView.isGroupExpanded(i)) && (i == group))) {
for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
View listItem = listAdapter.getChildView(i, j, false, null,
listView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
int height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
/* if (height < 10)
height = 200;*/
params.height = height;
listView.setLayoutParams(params);
listView.requestLayout();
}
private void fn_data() {
String str_data = loadJSONFromAsset();
try {
JSONObject jsonObject_country = new JSONObject(str_data);
JSONArray jsonArray_country = jsonObject_country.getJSONArray("country");
al_main = new ArrayList<>();
for (int i = 0; i < jsonArray_country.length(); i++) {
Model_country obj_country = new Model_country();
JSONObject jsonObject = jsonArray_country.getJSONObject(i);
JSONArray jsonArray_dishes = jsonObject.getJSONArray("dishes");
ArrayList<Model_Dish> al_dishes = new ArrayList<>();
for (int j = 0; j < jsonArray_dishes.length(); j++) {
JSONObject jsonObject_dishes = jsonArray_dishes.getJSONObject(j);
Model_Dish obj_dish = new Model_Dish();
obj_dish.setStr_name(jsonObject_dishes.getString("dishname"));
obj_dish.setStr_description(jsonObject_dishes.getString("description"));
obj_dish.setStr_image(jsonObject_dishes.getString("image"));
al_dishes.add(obj_dish);
}
obj_country.setAl_state(al_dishes);
obj_country.setStr_country(jsonObject.getString("name"));
// obj_country.setStr_country (jsonObject.getString("image"));
al_main.add(obj_country);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void setExpandableListViewHeightBasedOnChildren(ExpandableListView expandableListView) {
CountryAdapter adapter = (CountryAdapter) expandableListView.getExpandableListAdapter();
if (adapter == null) {
return;
}
int totalHeight = expandableListView.getPaddingTop() + expandableListView.getPaddingBottom();
for (int i = 0; i < adapter.getGroupCount(); i++) {
View groupItem = adapter.getGroupView(i, false, null, expandableListView);
groupItem.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (expandableListView.isGroupExpanded(i)) {
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
View listItem = adapter.getChildView(i, j, false, null, expandableListView);
listItem.setLayoutParams(new ViewGroup.LayoutParams(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED));
listItem.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = expandableListView.getLayoutParams();
int height = totalHeight + expandableListView.getDividerHeight() * (adapter.getGroupCount() - 1);
if (height < 10)
height = 100;
params.height = height;
expandableListView.setLayoutParams(params);
expandableListView.requestLayout();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("dishes.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
Log.e(TAG, "Json response " + json);
return json;
}
public void fn_selectedPosition(int group, int child) {
fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("name", al_main.get(group).getStr_country());
bundle.putString("des", al_main.get(group).getAl_state().get(child).getStr_description());
bundle.putString("dish", al_main.get(group).getAl_state().get(child).getStr_name());
bundle.putString("image", al_main.get(group).getAl_state().get(child).getStr_image());
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, "HomeFragment").addToBackStack("null").commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
tv_name.setText(al_main.get(group).getStr_country());
}
activity_main:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:background="#234E6F"
android:layout_height="60dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#ffffff"
android:layout_centerInParent="true"
android:textStyle="bold"
android:id="#+id/tv_name"/>
<ImageView
android:layout_width="25dp"
android:layout_centerVertical="true"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:src="#drawable/menu_icon"/>
<RelativeLayout
android:layout_width="40dp"
android:id="#+id/rl_menu"
android:layout_height="match_parent"></RelativeLayout>
</RelativeLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#FFFFFF">
<include layout="#layout/menu_layout"></include>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
You can use expandable listview for this. use custom adapter which will have textview and imageview. set image and text using expandable listview adapter. you can use custom adapter for child and parent both
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
if (view == null)
view = layoutInflater.inflate(R.layout.row_comment, viewGroup, false);
TextView username=(TextView) view.findViewById(R.id.userName);
((ImageView) view.findViewById(R.id.img_hifi)).setImageResource(R.drawable.high_5_icon_highlited);
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null)
view = layoutInflater.inflate(R.layout.row_comment, viewGroup, false);
view.setBackgroundColor(Color.parseColor("#FFCC00"));
((TextView) view.findViewById(R.id.userName)).setText(getChild(i, i1).getUser_name() + " ");
((TextView) view.findViewById(R.id.userName)).setTextColor(Color.BLACK);
return view;
}

Use TabAdapter for scroll horizontal and vertical

Basically I already have a HorizontalAdapters which means I can only swipe left and right and in those swipes I have 3 pages.
public class HorizontalViewPager extends FragmentPagerAdapter {
public HorizontalViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return ChatFragment.create();
case 1:
return EmptyFragment.create();
case 2:
return StoryFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
Now I'm trying to add two more pages on top and below my EmptyFragment so when I swipe up it goes to another page and also when I swipe down.
I have my two fragments that I want to put on top and below my emptyfragment.
This is my MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//VerticalViewPager
me.kaelaela.verticalviewpager.VerticalViewPager verticalViewPager = findViewById(R.id.am_scrollView);
VerticalViewPager scrollViewAdapter = new VerticalViewPager(getSupportFragmentManager());
verticalViewPager.setAdapter(scrollViewAdapter);
verticalViewPager.setPageTransformer(false, new DefaultTransformer());
//HorizontalViewPager
View background = findViewById(R.id.am_background_view);
ViewPager viewPager = findViewById(R.id.am_view_pager);
HorizontalViewPager adapter = new HorizontalViewPager(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1);
And this is my EmptyFragment
public class EmptyFragment extends Fragment {
public static EmptyFragment create(){
return new EmptyFragment();
}
If you dont under stand what I'm trying to do its basically just a page that you can swipe left,right,up,and down and it views different pages.
MainLayout File
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="c.kristofer.jax2.MainActivity">
<View
android:id="#+id/am_background_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"/>
<me.kaelaela.verticalviewpager.VerticalViewPager
android:id="#+id/am_scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.v4.view.ViewPager
android:id="#+id/am_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
And my two layout files that I want to put above and below my emptyfragment
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
</LinearLayout>
And
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/yellow">
</LinearLayout>
I answer the exact same question here. Probably you guys do the same class, so be attention with ctrl+c and ctrl+v code.
I will copy
Getting the base from here.
Create a GestureDetectorCompat object
GestureDetectorCompat gestureDetectorCompat;
and override onTouchEvent in the activity
#Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetectorCompat.onTouchEvent(event);
return true;
}
or if you want to detect on some view then you can Override onTouch
someView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
gestureDetectorCompat.onTouchEvent(motionEvent);
return false;
}
});
and initialize gestureDetectorCompat as follows somewhere preferably in onCreate() and you are done.
gestureDetectorCompat = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
float angle = (float) Math.toDegrees(Math.atan2(e1.getY() - e2.getY(), e2.getX() - e1.getX()));
if (angle > -45 && angle <= 45) {
if(goRight != 5) mainContainer.setCurrentItem(goRight);
return true;
}
if (angle >= 135 && angle < 180 || angle < -135 && angle > -180) {
if(goLeft != 5) mainContainer.setCurrentItem(goLeft);
return true;
}
if (angle < -45 && angle >= -135) {
if(goUp != 5)mainContainer.setCurrentItem(goUp);
return true;
}
if (angle > 45 && angle <= 135) {
if(goDown != 5)mainContainer.setCurrentItem(goDown);
return true;
}
return false;
}
});
Then you can use mainContainer.setCurrentItem(number); to go to other position/fragment.
Don't forget that the number change if you are in different number. Like this
switch(adapter.getCurrentItem()){
case 0:
goRight = 2;
goLeft = 4;
goUp = 3;
goDown = 1;
break;
case 1:
goRight = 5;
goLeft = 5;
goUp = 0;
goDown = 5;
break;
case 2:
goRight = 5;
goLeft = 0;
goUp = 5;
goDown = 5;
break;
case 3:
goRight = 5;
goLeft = 5;
goUp = 5;
goDown = 0;
break;
case 4:
goRight = 0;
goLeft = 5;
goUp = 5;
goDown = 5;
break;
}
When you are in the fragment 4 you can only go to 0, not 2 if you swipe left-right.
And this should be your adapter
public class SwipeViewPager extends FragmentPagerAdapter {
public SwipeViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return EmptyFragment.create();
case 1:
return StoryFragment.create();
case 2:
return ExtrasFragment.create();
case 3:
return ChatFragment.create();
case 4:
return SettingsFragment.create();
}
return null;
}
#Override
public int getCount() {
return 5;
}
Create one more Fragment with VerticalViewPager inside it and add top, empty and bottom to view pager and set default page to empty page fragment
MainActivity layout should be as below
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="c.kristofer.jax2.MainActivity">
<View
android:id="#+id/am_background_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/green"/>
<android.support.v4.view.ViewPager
android:id="#+id/am_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
The HorizontalViewPager should be like below see VerticalScrollFragment
public class HorizontalViewPager extends FragmentPagerAdapter {
public HorizontalViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ChatFragment.create();
case 1:
return VerticalScrollFragment.create();
case 2:
return StoryFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Then VerticalFragment layout vertical.xml file will be like this
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="c.kristofer.jax2.MainActivity">
<me.kaelaela.verticalviewpager.VerticalViewPager
android:id="#+id/am_scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Then VerticalFragment class will be like below
public class VerticalScrollFragment extends Fragment {
VerticalViewPager verticalViewPager;
VerticalViewPagerAdapter verticalPageAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vertical, null);
verticalViewPager = view.findViewById(R.id.am_scrollView);
verticalPageAdapter = new VerticalViewPagerAdapter(getChildFragmentManager());
verticalViewPager.setAdapter(verticalPageAdapter)
return inflater.inflate(R.layout.vertical, null);
}
public class VerticalViewPagerAdapter extends FragmentPagerAdapter {
public HorizontalViewPager(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TopFragment.create();
case 1:
return EmptyFragment.create();
case 2:
return BottomFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
}

How to change selected tab title textSize in Android

I am trying to find a way to change text size of Tab Title when selected. Until now without exit. Hope someone can help me.
My code bellow:
XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab_layout"
app:tabSelectedTextColor="#android:color/holo_orange_dark"
app:tabTextAppearance="#style/textAppearance">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager_view"/>
Style used for tabTextAppearance:
<style name="textAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">18sp</item>
<item name="android:textStyle">bold</item>
</style>
My adapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final Resources resources;
private static final int num = 3;
public ViewPagerAdapter(FragmentManager fm, Resources resources) {
super(fm);
this.resources = resources;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentA();
break;
case 1:
fragment = new FragmentB();
break;
case 2:
fragment = new FragmentC();
break;
}
return fragment;
}
#Override
public int getCount() {
return num;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
switch (position) {
case 0:
title = "A";
break;
case 1:
title = "B";
break;
case 2:
title = "C";
break;
}
return title;
}
}
And My Carousel Fragment class:
public class CarouselFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter viewPagerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_carousel, container, false);
tabLayout = (TabLayout)root.findViewById(R.id.tab_layout);
viewPager = (ViewPager)root.findViewById(R.id.pager_view);
setHasOptionsMenu(true);
return root;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), getResources());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setSelectedTabIndicatorColor(Color.RED);
tabLayout.setupWithViewPager(viewPager);
}else {
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here i should do something, but what???
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//here i should do something, but what???
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
Many thanks in advance!
use this code
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
TextView tabTextView = new TextView(this);
tab.setCustomView(tabTextView);
tabTextView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
tabTextView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
tabTextView.setText(tab.getText());
if (i == 0) {
tabTextView.setTextSize(16);
}
}
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
ViewGroup vgTab = (ViewGroup) vg.getChildAt(tab.getPosition());
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTextSize(16);
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
ViewGroup vgTab = (ViewGroup) vg.getChildAt(tab.getPosition());
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTextSize(14);
}
}
}
}
I would recommend to set custom tab.
First you need to initiate your custom tabs, otherwise it won't change anything.
Create a new layout with a TextView (you can add whatever you want to be in each tab).
In your onActivityCreated after your tabLayout.setupWithViewPager initiate your custom tabs:
for (int i = 0; i < 3; i++) { // 3 - A+B+C in your example
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
ViewGroup tabContainer = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.custom_tab_item, tabLayout, false);
if (tabContainer != null) {
TextView yourTv = (TextView) tabContainer.findViewById(R.id.tv);
yourTv.setTextSize(18);
tab.setCustomView(tabContainer);
}
}
}
Add listener tabLayout.addOnTabSelectedListener and Implement TabLayout.OnTabSelectedListener, In your onTabSelected use this:
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
View customView = tab.getCustomView();
if (customView != null) {
TextView yourTv = (TextView) customView.findViewById(R.id.tv);
if (yourTv != null) {
if (i == selectedTabIndex) {
yourTv.setTextSize(18);
} else {
yourTv.setTextSize(16);
}
}
}
}
}
You can set your own view to the TabLayout's individual tabs and you can change the size latter on the tab selection-
Here is the code hint -
TabLayout mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
TabLayout.Tab tabOne = mTabLayout.newTab();
tabOne.setCustomView(getLayoutInflater().inflate(R.layout.item_tab, mTabLayout, false));
mTabLayout.addTab(tabOne);
TabLayout.Tab tabTwo = mTabLayout.newTab();
tabTwo.setCustomView(getLayoutInflater().inflate(R.layout.item_tab, mTabLayout, false));
mTabLayout.addTab(tabTwo);
tabTwo.select();
// mTabLayout.setupWithViewPager(mViewPager);
if (getResources().getDisplayMetrics().widthPixels > getResources().getDisplayMetrics().heightPixels) {
mTabLayout.setTabMode(TabLayout.MODE_FIXED);
} else {
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
((TextView) tab.getCustomView().findViewById(R.id.text1)).setTextSize(16);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
((TextView) tab.getCustomView().findViewById(R.id.text1)).setTextSize(13);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
iteb_tab.xml can be like -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:text="One"
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
You can further synchronize the selection with viewpager page change as
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mTabLayout.getTabAt(position).select();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Edit
You can further reduce your effort by setting your tab titles from the adapter itself -
PagerAdapter mPagerAdapter = mViewPager.getAdapter();
for (int position = 0; position < mPagerAdapter.getCount(); position++) {
View view = (getLayoutInflater().inflate(R.layout.item_tab, mTabLayout, false));
TextView label = (TextView) view.findViewById(R.id.text1);
label.setText(mPagerAdapter.getPageTitle(position));
TabLayout.Tab tab = mTabLayout.newTab();
tab.setCustomView(view);
mTabLayout.addTab(tab);
}
Here is how it looks -

How to draw a layout inside layout

I have aplication where after clicking on Statistics i call StatsFragment. StatsFragment uses fragment_stats xml layout that has there a TabLayout and CustomViewPager. However when i clicked on Statistics so my StatsFragment is called data are not drawn there. After i click on some tab data will be there.
Problem is with initial drawing. From How can you tell when a layout has been drawn? i know i shall use somehow ViewTreeObserver but cant find the way where and how.
fragment_stats xml file:
<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=".StatsFragment">
<!-- TODO: Update blank fragment layout -->
<!--android:elevation="6dp"-->
<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"
/>
<pv239.fi.muni.cz.moneymanager.CustomViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"
>
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</pv239.fi.muni.cz.moneymanager.CustomViewPager>
</RelativeLayout>
tab_fragment xml file:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/gridViewScreenStats">
<com.jjoe64.graphview.GraphView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/graph" />
<GridLayout
android:id="#+id/stats"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/graph"
android:layout_gravity="center"
android:background="#drawable/box"
android:layout_margin="10dp"
android:rowCount="5"
android:columnCount="2"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Starting balance: "
android:paddingLeft="10dp"
android:id="#+id/startBalanceLabel"
android:layout_row="0"
android:layout_column="0"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/startBalanceLabel"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/startBalance"
android:layout_row="0"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/startBalance"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Ending balance: "
android:paddingLeft="10dp"
android:id="#+id/endBalanceLabel"
android:layout_row="1"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/startBalance"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:layout_toRightOf="#id/endBalanceLabel"
android:id="#+id/endBalance"
android:layout_row="1"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Incomes: "
android:layout_below="#id/endBalanceLabel"
android:id="#+id/incomeStats"
android:layout_row="2"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:textColor="#color/recordPositiveValue"
android:id="#+id/incomeSumStats"
android:layout_below="#id/endBalance"
android:textAlignment="textEnd"
android:layout_row="2"
android:layout_column="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Expenses:"
android:id="#+id/expenseStats"
android:layout_row="3"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:textColor="#color/recordNegativeValue"
android:id="#+id/expenseSumStats"
android:textAlignment="textEnd"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_row="3"
android:layout_column="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="+/- status:"
android:id="#+id/actualStats"
android:layout_row="4"
android:layout_column="0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/actualSumStats"
android:textColor="#color/recordPositiveValue"
android:textAlignment="textEnd"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_row="4"
android:layout_column="1" />
</GridLayout>
<!-- Income records -->
<ListView
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="#drawable/box"
android:layout_below="#id/stats"
android:layout_margin="10dp"
android:id="#+id/listViewIncomeStats"
android:nestedScrollingEnabled="true"/>
<!-- Expenses records -->
<ListView
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="#drawable/box"
android:layout_below="#+id/listViewIncomeStats"
android:layout_margin="10dp"
android:id="#+id/listViewExpences"
android:nestedScrollingEnabled="true"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
StatsFragment java file:
public class StatsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ListView incomeListView;
private ListView expensesListView;
private OnStatsInteractionListener mListener;
public StatsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment StatsFragment.
*/
// TODO: Rename and change types and number of parameters
public static StatsFragment newInstance(String param1, String param2) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
StatsFragment fragment = new StatsFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_stats, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TabLayout tabLayout = (TabLayout) getView().findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("7 days"));
tabLayout.addTab(tabLayout.newTab().setText("1 month"));
tabLayout.addTab(tabLayout.newTab().setText("1 year"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final CustomViewPager viewPager = (CustomViewPager) getView().findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setPagingEnabled(false);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
// TextView txt = (TextView) (adapter.getItem(tab.getPosition())).getView().findViewById(R.id.startMonthStats);
processChanges((adapter.getItem(tab.getPosition())).getView(),tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onStatsInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnStatsInteractionListener {
// TODO: Update argument type and name
void onStatsInteraction(Uri uri);
}
private Date numbersToDate(int daysBack, int monthsBack, int yearsBack)
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, daysBack *(-1));
cal.add(Calendar.MONTH, monthsBack *(-1));
cal.add(Calendar.YEAR, yearsBack *(-1));
return cal.getTime();
}
public void processChanges(View tabView, int tabNum)
{
int d =7;
int m =0;
int y =0;
MMDatabaseHelper sloh = MMDatabaseHelper.getInstance(getActivity());
if (tabNum == 1)
{
d =0;
m =1;
y =0;
}
else if (tabNum == 2)
{
d =0;
m =0;
y =1;
}
createGraph(tabView, d, m, y, sloh);
setBalances(tabView, d, m, y, sloh);
setListValues(tabView, d, m, y, sloh);
}
private void setListValues(View tabView, int d, int m, int y,MMDatabaseHelper sloh) {
// Creating incomes list
incomeListView = (ListView) tabView.findViewById(R.id.listViewIncomeStats);
Cursor incomeRecords = sloh.getRecordsInRange(">",d,m,y);
RecordsDbToStatsAdapter incomeAdapter = new RecordsDbToStatsAdapter(this.getContext(), incomeRecords, 0);
incomeListView.setAdapter(incomeAdapter);
// Creating expenses list
expensesListView = (ListView) tabView.findViewById(R.id.listViewExpences);
Cursor expensesRecords = sloh.getRecordsInRange("<",d,m,y);
RecordsDbToStatsAdapter expensesAdapter = new RecordsDbToStatsAdapter(this.getContext(), expensesRecords, 0);
expensesListView.setAdapter(expensesAdapter);
}
private void setBalances(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
//Fetching Values of incomes and expenses and balances
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
format.setMaximumFractionDigits(2);
TextView incSum = (TextView) tabView.findViewById(R.id.incomeSumStats);
Integer helpInc = sloh.getSumRecordsInRange(">",d,m,y);
BigDecimal incValue = new BigDecimal(helpInc.toString());
incSum.setText(format.format(incValue.abs().setScale(2).doubleValue()));
TextView expSum = (TextView) tabView.findViewById(R.id.expenseSumStats);
Integer helpExp = sloh.getSumRecordsInRange("<",d,m,y);
BigDecimal expValue = new BigDecimal(helpExp.toString());
expSum.setText(format.format(expValue.abs().setScale(2).doubleValue()));
TextView startBal = (TextView) tabView.findViewById(R.id.startBalance);
BigDecimal startValue = new BigDecimal(sloh.getStartingBal(numbersToDate(d,m,y)).toString());
startBal.setText(format.format(startValue.abs().setScale(2).doubleValue()));
TextView endBal = (TextView) tabView.findViewById(R.id.endBalance);
BigDecimal endValue = new BigDecimal(sloh.getEndingBal().toString());
endBal.setText(format.format(endValue.abs().setScale(2).doubleValue()));
TextView actState = (TextView) tabView.findViewById(R.id.actualSumStats);
actState.setText(format.format(new BigDecimal(helpInc + helpExp).setScale(2).doubleValue()));
}
private void createGraph(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
// Graph rendering section
// Cursor graphCursor = sloh.getRecordsInRange(null,d,m,y);
// graphCursor.moveToFirst();
int days=0;
if (d == 7) { days = d;}
if (m == 1) { days = 28;}
if (y == 1) { days = 365;}
ArrayList numList = new ArrayList();
GraphView graph = (GraphView) tabView.findViewById(R.id.graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] { });
Calendar day = Calendar.getInstance();
day.set(Calendar.HOUR_OF_DAY,0);
day.set(Calendar.MINUTE,0);
day.set(Calendar.SECOND,0);
for(int i=days; i>0;i--) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR,-i);
day.setTime(cal.getTime());
Log.i("TIME",cal.getTime().toString());
numList.add(sloh.getCurrentBalanceForOneDay(cal.getTime()));
series.appendData(new DataPoint(day.getTime(),sloh.getCurrentBalanceForOneDay(cal.getTime())),true,days);
}
Log.i("Pole", numList.toString());
graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(getActivity()));
graph.getGridLabelRenderer().setNumHorizontalLabels(4); // only 4 because of the space
graph.addSeries(series);
}
}
From what I can tell, you're not doing the right things at the right time.
When the onCreateView of your fragment is called, you inflate the corresponding layout but do not set any value in there.
Simply swapping all the code you have in onActivityCreated into the onCreateView should do the trick, as follow :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_stats, container, false);
TabLayout tabLayout = (TabLayout)layout.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("7 days"));
tabLayout.addTab(tabLayout.newTab().setText("1 month"));
tabLayout.addTab(tabLayout.newTab().setText("1 year"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final CustomViewPager viewPager = (CustomViewPager) layout.findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setPagingEnabled(false);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
processChanges((adapter.getItem(tab.getPosition())).getView(),tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return (layout);
}
EDIT : After having a second (and closer) look at your code, the best idea would be to have fragments managing your tabs, so that you could put your logic in there (and place them in each tab). To do so :
Step 1 : Create a new fragment class for your pages
public abstract class PageFragment extends Fragment {
private int pageNumber;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt("page_number", page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return (fragment);
}
public PageFragment(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
pageNumber = getArguments().getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.tab_fragment, container, false);
//Get all the views you need for your page, using
//layout.findViewById();
//Then you will need to call processChanges for that page
processChanges(layout, pageNumber);
return (layout);
}
//Also add here all the logic associated with processChanges
}
Step 2 will be to get references of your fragments in your StatsFragment, and add these fragments to your pager :
private PageFragment pageOne;
private PageFragment pageTwo;
private PageFragment pageThree;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_stats, container, false);
TabLayout tabLayout = (TabLayout)layout.findViewById(R.id.tab_layout);
pageOne = PageFragment.newInstance(0);
pageTwo = PageFragment.newInstance(1);
pageThree = PageFragment.newInstance(2);
tabLayout.addFragment(pageOne, "7 days");
tabLayout.addFragment(pageTwo, "1 month");
tabLayout.addFragment(pageThree, "1 year");
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
}
Step 3 : You will finally need to have a custom pager adapter to hold the titles and the fragments of your pager :
public class MyViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mTitles = new ArrayList<>();
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return (mFragments.get(position));
}
#Override
public int getCount() {
return (mFragments.size());
}
#Override
public String getPageTitle(int position) {
return (mTitles.get(position));
}
}
To use it, simply create it via (instead of your PagerAdapter)
final MyPagerAdapter adapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
According to Nsimon i update current state. This solved problem with initial screen for me. Big thank to NSimon.
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return (mFragments.get(position));
}
#Override
public int getCount() {
return (mFragments.size());
}
#Override
public String getPageTitle(int position) {
return (mTitles.get(position));
}
}
PageFragment:
public class PageFragment extends Fragment {
private int pageNumber;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt("page_number", page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return (fragment);
}
public PageFragment(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
pageNumber = getArguments().getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.tab_fragment, container, false);
//Get all the views you need for your page, using
//layout.findViewById();
//Then you will need to call processChanges for that page
processChanges(layout, pageNumber);
return (layout);
}
public void processChanges(View tabView, int tabNum)
{
int d =7;
int m =0;
int y =0;
MMDatabaseHelper sloh = MMDatabaseHelper.getInstance(getActivity());
if (tabNum == 1)
{
d =0;
m =1;
y =0;
}
else if (tabNum == 2)
{
d =0;
m =0;
y =1;
}
createGraph(tabView, d, m, y, sloh);
setBalances(tabView, d, m, y, sloh);
setListValues(tabView, d, m, y, sloh);
}
private void setListValues(View tabView, int d, int m, int y,MMDatabaseHelper sloh) {
// Creating incomes list
ListView incomeListView = (ListView) tabView.findViewById(R.id.listViewIncomeStats);
Cursor incomeRecords = sloh.getRecordsInRange(">",d,m,y);
RecordsDbToStatsAdapter incomeAdapter = new RecordsDbToStatsAdapter(this.getContext(), incomeRecords, 0);
incomeListView.setAdapter(incomeAdapter);
// Creating expenses list
ListView expensesListView = (ListView) tabView.findViewById(R.id.listViewExpences);
Cursor expensesRecords = sloh.getRecordsInRange("<",d,m,y);
RecordsDbToStatsAdapter expensesAdapter = new RecordsDbToStatsAdapter(this.getContext(), expensesRecords, 0);
expensesListView.setAdapter(expensesAdapter);
}
private Date numbersToDate(int daysBack, int monthsBack, int yearsBack)
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, daysBack *(-1));
cal.add(Calendar.MONTH, monthsBack *(-1));
cal.add(Calendar.YEAR, yearsBack *(-1));
return cal.getTime();
}
private void setBalances(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
//Fetching Values of incomes and expenses and balances
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.getDefault());
format.setMaximumFractionDigits(2);
TextView startBal = (TextView) tabView.findViewById(R.id.startBalance);
BigDecimal startValue = new BigDecimal(sloh.getStartingBal(numbersToDate(d,m,y)).toString());
startBal.setText(String.valueOf(startValue.setScale(2).doubleValue()));
TextView endBal = (TextView) tabView.findViewById(R.id.endBalance);
BigDecimal endValue = new BigDecimal(sloh.getEndingBal().toString());
endBal.setText(String.valueOf(endValue.setScale(2).doubleValue()));
TextView incSum = (TextView) tabView.findViewById(R.id.incomeSumStats);
Integer helpInc = sloh.getSumRecordsInRange(">",d,m,y);
BigDecimal incValue = new BigDecimal(helpInc.toString());
incSum.setText(String.valueOf(incValue.setScale(2).doubleValue()));
TextView expSum = (TextView) tabView.findViewById(R.id.expenseSumStats);
Integer helpExp = sloh.getSumRecordsInRange("<",d,m,y);
BigDecimal expValue = new BigDecimal(helpExp.toString());
expSum.setText(String.valueOf(expValue.setScale(2).doubleValue()));
}
private void createGraph(View tabView, int d, int m, int y, MMDatabaseHelper sloh) {
// Graph rendering section
// Cursor graphCursor = sloh.getRecordsInRange(null,d,m,y);
// graphCursor.moveToFirst();
int days=0;
if (d == 7) { days = d;}
if (m == 1) { days = 28;}
if (y == 1) { days = 365;}
ArrayList numList = new ArrayList();
GraphView graph = (GraphView) tabView.findViewById(R.id.graph);
LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[] { });
Calendar day = Calendar.getInstance();
day.set(Calendar.HOUR_OF_DAY,0);
day.set(Calendar.MINUTE,0);
day.set(Calendar.SECOND,0);
for(int i=days; i>0;i--) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR,-i);
day.setTime(cal.getTime());
Log.i("TIME",cal.getTime().toString());
numList.add(sloh.getCurrentBalanceForOneDay(cal.getTime()));
series.appendData(new DataPoint(day.getTime(),sloh.getCurrentBalanceForOneDay(cal.getTime())),true,days);
}
Log.i("Pole", numList.toString());
graph.getGridLabelRenderer().setLabelFormatter(new DateAsXAxisLabelFormatter(getActivity()));
graph.getGridLabelRenderer().setNumHorizontalLabels(4); // only 4 because of the space
graph.addSeries(series);
}
}
StatsFragment:
private PageFragment pageOne;
private PageFragment pageTwo;
private PageFragment pageThree;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_stats, container, false);
TabLayout tabLayout = (TabLayout)layout.findViewById(R.id.tab_layout);
pageOne = PageFragment.newInstance(0);
pageTwo = PageFragment.newInstance(1);
pageThree = PageFragment.newInstance(2);
tabLayout.addTab(tabLayout.newTab().setText("7 days"));
tabLayout.addTab(tabLayout.newTab().setText("1 month"));
tabLayout.addTab(tabLayout.newTab().setText("1 year"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final CustomViewPager viewPager = (CustomViewPager) layout.findViewById(R.id.pager);
final ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(pageOne,"7 days");
adapter.addFragment(pageTwo,"1 month");
adapter.addFragment(pageThree,"1 year");
viewPager.setAdapter(adapter);
viewPager.setPagingEnabled(false);
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) {
}
});
return layout;
}

Android simple tabs with toolbar

I've been struggling with tab implementation in my application and seen a lot of resources on the matter but nothing appears to be working for me. I just want 4 simple tabs with icons above my toolbar, that's all. Can someone help me out on achieving this?
Here's my code if needed:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class ProjectCreateScreen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondary_layout1);
Toolbar toolbar = (Toolbar) findViewById(R.id.AwesomeBar);
setSupportActionBar(toolbar);
}
public void displayProjectOptions (View view) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_primary, menu);
return true;
}
final ArrayList<String> listItems=new ArrayList<String>();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addButton) {
final TextView noProject = (TextView) findViewById(R.id.NOPROJECT);
final ListAdapter addAdapter = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.listFrame, listItems);
final ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(addAdapter);
noProject.setVisibility(View.GONE);
lv.setVisibility(View.VISIBLE);
listItems.add("New Project");
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent switchToEdit = new Intent(ProjectCreateScreen.this,
teamCreateScreen.class);
startActivity(switchToEdit);
}
});
}
return super.onOptionsItemSelected(item);
}
}
And xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rl">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
android:id="#+id/AwesomeBar"
android:background="#color/custom_white">
</android.support.v7.widget.Toolbar>
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="#string/noProjectsNotice"
android:id="#+id/NOPROJECT"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="16sp"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AwesomeBar"
android:id="#+id/lv"
android:visibility="invisible">
</ListView>
If you are using toolbar you need to use SlidingTabLayout for tabs in toolbar as follows
TabFragment.java
public class TabFragment extends Fragment {
private SlidingTabLayout mSlidingTabLayout;
private MyActivityAdapter mAdapter;
private ViewPager mViewPager;
private Menu mMenu;
private ScreenNames mScreenName = ScreenNames.UNRAVELING_ME;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_swipe, container, false);
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.unravel_secondary_red));
mSlidingTabLayout.setDistributeEvenly(true);
mSlidingTabLayout.setBackgroundColor(Color.parseColor("#F7F7F7"));
mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener (){
#Override
public void onPageSelected(int position)
{
if(position == 0){
}
else {
}
}
#Override
public void onPageScrollStateChanged(int state)
{
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
});
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mAdapter = new MyActivityAdapter(this, getChildFragmentManager());
mViewPager.setAdapter(mAdapter);
mSlidingTabLayout.setViewPager(mViewPager);
return view;
}
fragment_swipe.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.unravel.widget.SlidingTabLayout
android:id="#+id/sliding_tabs"
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="0px"
android:layout_weight="1"/>
</LinearLayout>
MyActivityAdapter.java
public class MyActivityAdapter extends FragmentPagerAdapter {
private MyActivityFragment mFragment;
public MyActivityAdapter(MyActivityFragment fragment, FragmentManager fm) {
super(fm);
mFragment = fragment;
}
#Override
public Fragment getItem(int i) {
if (i == 0) {
return new fragment1();
}
else {
return new fragment2();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "first tab";
} else {
return "second tab";
}
}
}
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
Fragment2.java
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
SlidingTabLayout.java
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows COMPLETE control over the colors drawn in the tab layout. Set with
* {#link #setCustomTabColorizer(TabColorizer)}.
*/
public interface TabColorizer {
/**
* #return return the color of the indicator used when {#code position} is selected.
*/
int getIndicatorColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 18;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private boolean mDistributeEvenly;
private ViewPager mViewPager;
private SparseArray<String> mContentDescriptions = new SparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {#link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {#link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
public void setDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Set the {#link ViewPager.OnPageChangeListener}. When using {#link SlidingTabLayout} you are
* required to set any {#link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* #see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* #param layoutResId Layout id to be inflated
* #param textViewId id of the {#link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {#link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(true);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
}
}
public void setContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
SlidingTabStrip.java
class SlidingTabStrip extends LinearLayout {
private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 2;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;
private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;
private final int mDefaultBottomBorderColor;
private int mSelectedPosition;
private float mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
}
SlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
final float density = getResources().getDisplayMetrics().density;
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorForeground, outValue, true);
final int themeForegroundColor = outValue.data;
mDefaultBottomBorderColor = setColorAlpha(themeForegroundColor,
DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.setColor(mDefaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
}
void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
}
void setSelectedIndicatorColors(int... colors) {
// Make sure that the custom colorizer is removed
mCustomTabColorizer = null;
mDefaultTabColorizer.setIndicatorColors(colors);
invalidate();
}
void onViewPagerPageChanged(int position, float positionOffset) {
mSelectedPosition = position;
mSelectionOffset = positionOffset;
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
/**
* Set the alpha value of the {#code color} to be the given {#code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {#code color1} and {#code color2} using the given ratio.
*
* #param ratio of which to blend. 1.0 will return {#code color1}, 0.5 will give an even blend,
* 0.0 will return {#code color2}.
*/
private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
private int[] mIndicatorColors;
#Override
public final int getIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
void setIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
}
}

Categories

Resources