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;
}
}
}
Related
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!
There are two problems which i am trying to solve.I will accept your answer even if you solve one:
1)My tabLayout does not show the title of the current page.It does not show any text.
2)I use instance of the same fragment across the viewPager.Each fragment fetches some data from net and displays in listView.When i move pages slowly across the viewPager all fragments work properly.But when i move fast or use tabs to reach another page some pages never load.Why would it be?
Activity:
public class WorldNews extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_world_news);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
FragmentPageAdapter adapter = new FragmentPageAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager,true);
tabLayout.
}
}
Adapter:
public class FragmentPageAdapter extends FragmentStatePagerAdapter {
private String[] tabTitles = new String[]{"Tab1", "Tab2","Tab3" ,"Tab4" ,"Tab5","Tab6","Tab7","Tab8","Tab9","Tab10","Tab11","Tab12","Tab13","Tab14","Tab15"
,"Tab16","Tab17","Tab18","Tab19"};
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Log.d("Adapter","Case 0 called");
return new LisViewFragment2();
case 1:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=al-jazeera-english&sortBy=top&apiKey=6de");
case 2:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=associated-press&sortBy=top&apiKey=6de");
case 3:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=6de");
case 4:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=cnn&sortBy=top&apiKey=6de");
case 5:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=6de");
case 6:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=independent&sortBy=top&apiKey=6de");
case 7:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=metro&sortBy=top&apiKey=6de");
case 8:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=mirror&sortBy=top&apiKey=6de");
case 9:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=newsweek&sortBy=top&apiKey=6de");
case 10:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=new-york-magazine&sortBy=top&apiKey=6de");
case 11:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=reddit-r-all&sortBy=top&apiKey=6de");
case 12:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=reuters&sortBy=top&apiKey=6de");
case 13:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-guardian-uk&sortBy=top&apiKey=6de");
case 14:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-hindu&sortBy=top&apiKey=6de");
case 15:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=67de");
case 16:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-new-york-times&sortBy=top&apiKey=6de");
case 17:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-telegraph&sortBy=top&apiKey=6de");
default:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=usa-today&sortBy=top&apiKey=6de");
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public int getCount() {
return 19;
}
}
Here is the layout:
<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.android.gametalks.Activity.WorldNews">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager
android:layout_below="#id/sliding_tabs"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
Here is the fragment:
public class ListViewFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<GameNews>> {
public static ListViewFragment newInstance(String url) {
Log.d("ListViewFragment","newInstance created");
ListViewFragment f = new ListViewFragment();
// Supply url input as an argument.
Bundle args = new Bundle();
args.putString("url", url);
f.setArguments(args);
return f;
}
List<GameNews> TotalNews;
ListView gameListView;
LinearLayout emptyView;
Button retryButton;
ListAdapter adapter ;
private View progressBar;
final private int game_loader = 0;
ArrayList<String> urls = new ArrayList<>();
String mUrlString;
int index;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUrlString = getArguments().getString("url");
urls.add(mUrlString);
TotalNews = new ArrayList<GameNews>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
ArrayList<GameNews> gameList = new ArrayList<>();
adapter = new ListAdapter(getActivity(),gameList);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
emptyView = (LinearLayout) view.findViewById(R.id.no_internet_view);
progressBar = view.findViewById(R.id.progress_bar);
retryButton = (Button) view.findViewById(R.id.retry_button);
gameListView = getListView();
emptyView.setVisibility(View.INVISIBLE);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(adapter);
//If connected to net start the loader
if(isConnected())
{
getActivity().getSupportLoaderManager().restartLoader(game_loader, null, ListViewFragment.this);
if(progressBar.getVisibility() == View.VISIBLE)
{
Log.d("Fragment","progress bar is still visible");
}
}
//Otherwise show emptyView and hide listView
else
{
emptyView.setVisibility(View.VISIBLE);
gameListView.setVisibility(View.INVISIBLE);
}
}
#Override
public android.support.v4.content.Loader<List<GameNews>> onCreateLoader(int i, Bundle bundle) {
AdManager manager = new AdManager(getActivity());
return new FragmentLoader(getActivity(),urls,1000);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<List<GameNews>> loader, List<GameNews> games) {
progressBar.setVisibility(View.INVISIBLE);
adapter.clear();
TotalNews.addAll(games);
adapter.addAll(games);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<List<GameNews>> loader) {
adapter.clear();
}
//Method checks if there is internet
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
}
else {
return false;
}
}
}
You are not seeing the title because you have a lot of tabs and there's no place for title. Consider using TabLayout.MODE_SCROLLABLE
tabLayout.setTabMode (TabLayout.MODE_SCROLLABLE);
For First Question
try change tablayout in xml to:
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/red"
android:minHeight="?attr/actionBarSize"
android:elevation="10dp"
app:tabIndicatorColor="#color/black"
app:tabSelectedTextColor="#color/black"
app:tabTextColor="#color/white"
app:tabGravity="fill"
/>
choose your favorits colors
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 -
I have a relative layout which contains an image. I have like 10-20 images in drawable folder and a hashmap which stores these images.
On swiping below the image from left to right, it should change to next image.
On each swipe, it should change to next image from hashmap.
I am completely new to java and android programming and help in any way is appreciated.
This is what I have:
<?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: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"
tools:context="com.example.bschiranth.homework2_chiranthbs.MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/alice"
android:onClick="onClick"
android:clickable="true"
android:src="#drawable/alice"/>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/zoombar"
android:max="100"
android:progress="50"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
and my java:
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d("fling", "doing fling");
MovieData movieData = new MovieData();
HashMap hashMap = new HashMap();
for(int i=1;i<movieData.getSize();i++)
{
hashMap = movieData.getItem(i);
}
if(event1.getX()-event2.getX()> SWIPE_MIN_DISTANCE && Math.abs(velocityX)>SWIPE_THRESHOLD_VELOCITY)
{
Toast.makeText(Activity_Control.this,
"its flinging right to left", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.avatar);
}
if(event2.getX()-event1.getX()> SWIPE_MIN_DISTANCE && Math.abs(velocityX)>SWIPE_THRESHOLD_VELOCITY)
{
Toast.makeText(Activity_Control.this,
"its flinging left to right", Toast.LENGTH_SHORT).show();
imageView.setImageResource(R.drawable.avengers);
}
return true;
}
Better you can use view pager instead of imageview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/myfivepanelpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ViewPagerAdapter.java
import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class ViewPagerAdapter extends PagerAdapter {
Activity activity;
int imageArray[];
public ViewPagerAdapter(Activity act, int[] imgArra) {
imageArray = imgArra;
activity = act;
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
PageIndicatorActivity.java
public class PageIndicatorActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
R.drawable.antartica3, R.drawable.antartica4,
R.drawable.antartica5, R.drawable.antartica6,
R.drawable.antartica7, R.drawable.antartica8 };
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
This can be done by ViewFlipper as described below.
This is your Activity.xml file
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/view_flipper"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HowToUseActivity" >
<ImageView
android:id="#+id/imageHowToUse"
android:contentDescription="#string/app_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#mipmap/screen_1" />
</ViewFlipper>
declare required variables in your activity class
private int number = 0;
private float initialX;
private ImageView imageView;
in your Activity's onCreate(...) method retrieve the ImageView
imageView = (ImageView) findViewById(R.id.imageHowToUse);
override the method onTouchEvent(...) in same activity
#Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = event.getX();
break;
case MotionEvent.ACTION_UP:
float finalX = event.getX();
if (initialX > finalX) {
if (number >= 3) {
break;
}
next();
} else {
if(number <= 0) {
break;
}
previous();
}
break;
}
return false;
}
private void next() {
number++;
imageView.setImageResource(getImage());
}
private void previous() {
number--;
imageView.setImageResource(getImage());
}
then write method getImage() to get next image you want to display
private int getImage() {
int resource = R.mipmap.screen_1;
switch(number) {
case 0:
resource = R.mipmap.screen_1;
break;
case 1:
resource = R.mipmap.screen_2;
break;
case 2:
resource = R.mipmap.screen_3;
break;
}
return resource;
}
this is working code in my project. It'll help you.
NOTE : R.mipmap.screen_* is the image resource present in my resource directory.
I am trying to display a fragment in a ViewPager and I would like to have a button to replace the fragment in the ViewPager. I have managed to set up using examplesIi found on stackoverflow. However, how can I toggle between the 2 fragmentA and FragmentB.
Thank you so much.
My code is as follows :
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final FragmentManager mFragmentManager;
private Fragment mFragmentAtPos0;
private Fragment mFragmentAtPos1;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager=fm;
}
#Override
public int getItemPosition(Object object)
{
if (object instanceof FragmentA && mFragmentAtPos0 instanceof FragmentB)
return POSITION_NONE;
if (object instanceof FragmentB && mFragmentAtPos1 instanceof FragmentA)
return POSITION_NONE;
return POSITION_UNCHANGED;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position){
case 1:
if (mFragmentAtPos1 == null)
{
mFragmentAtPos1 = FragmentB.newInstance(new FirstPageFragmentListener()
{
public void onSwitchToNextFragment()
{
mFragmentManager.beginTransaction().remove(mFragmentAtPos1).commit();
mFragmentAtPos1 = new FragmentA();
notifyDataSetChanged();
showToast("in switchtoNextFragmentA ------------1");
}
});
}
return mFragmentAtPos1;
case 0:
if (mFragmentAtPos0 == null)
{
mFragmentAtPos0 = FragmentA.newInstance(new FirstPageFragmentListener()
{
public void onSwitchToNextFragment()
{
mFragmentManager.beginTransaction().remove(mFragmentAtPos0).commit();
mFragmentAtPos0 = new FragmentB();
notifyDataSetChanged();
showToast("in switchtoNextFragment");
}
});
}
return mFragmentAtPos0;
default: return null;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public class FragmentB extends Fragment {
Button button;
static FragmentB b;
static FirstPageFragmentListener fpl1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
return inflater.inflate(R.layout.frag_b, group, false);
}
public static Fragment newInstance(FirstPageFragmentListener firstPageFragmentListener) {
// TODO Auto-generated method stub
fpl1 = firstPageFragmentListener;
if (b == null)
b = new FragmentB();
return b;
}
public static FragmentB newInstance() {
if (b == null)
b = new FragmentB();
return b;
}
#Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
button = (Button) getActivity().findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fpl1.onSwitchToNextFragment();
}
});
}
}
UPDATE : layout file
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/lbltime"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:id="#+id/framelayout">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFCC" >
</android.support.v4.view.ViewPager>
</FrameLayout>
Its simple just do this
inside your button onClick method
Fragment f;
f = new FragmentTwo();
FragmentTransaction ft = getFragmentSupportManager().beginTransaction();
ft.replace(R.id.main_details_fragment_container, f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();