I'm developing an App using TabLayout and ViewPager.
As a result, I have set images to show in different fragments, eg. fragment_page1, fragment_page2, fragment_page3 etc. But images in Fragment_page1 are visible in all fragments. Please, how do I solve this issue?
This is my FragmentAdapter class
public class SimpleFragmentPageAdapter extends FragmentPagerAdapter {
private String[] tabtitle=new String[]{"Description","Directions","Developers","Chant Page","Chant Page",};
Context context;
private int pagecount=4;
public SimpleFragmentPageAdapter(FragmentManager fm, Context context) {
super(fm);
this.context=context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //Fragment # 0 - This will show DevelopersFragment
return DescriptionFragment.newInstance(0, "page # 0");
case 1: //Fragment # 0 - This will show Page1Fragment
return Page1Fragment.newInstance(1, "Chant # Page1");
case 2: //Fragment # 0 - This will show Page1Fragment
return Page1Fragment.newInstance(2, "Chant # Page2");
case 3: //Fragment # 0 - This will show Page1Fragment
return Page1Fragment.newInstance(3, "Chant # Page2");
//etc
default:
return null;
}
}
#Override
public int getCount() {
return pagecount;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return "Chant Page" + position;
}
}
This is my fragment_page1 xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:gravity="top|fill_vertical"
android:background="#efc393"
tools:context=".Page1Fragment">
<ScrollView
android:id="#+id/scroller"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/ImPage1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/page1_1" />
<ImageView
android:id="#+id/ImPage2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage1"
android:scaleType="fitXY"
android:src="#drawable/page1_2" />
<ImageView
android:id="#+id/ImPage3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage2"
android:scaleType="fitXY"
android:src="#drawable/page1_3" />
<ImageView
android:id="#+id/ImPage4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage3"
android:scaleType="fitXY"
android:src="#drawable/page1_4" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
This is my fragment_page2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:gravity="top|fill_vertical"
android:background="#efc393"
tools:context=".Page2Fragment">
<ScrollView
android:id="#+id/scroller"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/ImPage2a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/page2_1" />
<ImageView
android:id="#+id/ImPage2b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage2a"
android:scaleType="fitXY"
android:src="#drawable/page2_2" />
<ImageView
android:id="#+id/ImPage3c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage2b"
android:scaleType="fitXY"
android:src="#drawable/page2_3" />
</RelativeLayout>
This is the Activity that runs ViewPager
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab_layout"
app:tabSelectedTextColor="#ffffff"
app:tabMode="scrollable"
app:tabGravity="center"
app:tabTextColor="#A56302"
app:tabBackground="#drawable/pager"
app:tabIndicatorColor="#f10606"
app:tabIndicatorHeight="7dp">
</com.google.android.material.tabs.TabLayout>
<!-- Tab divider -->
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="#android:color/black" />
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contextClickable="true"
android:id="#+id/view_pager"
android:layout_marginBottom="70dp"
android:layout_below="#+id/tab_layout"
app:tabMode="fixed"
app:tabGravity="fill"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</androidx.viewpager.widget.ViewPager>
<!-- view for AdMob Banner Ad -->
<FrameLayout
android:id="#+id/ad_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true" />
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tips_7);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("CHANT");
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new com.aronti.chanthymnography.SimpleFragmentPageAdapter(getSupportFragmentManager(), this));
//Attach the page change listener inside the activity
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
Toast.makeText(Tips_7.this, "Selected Chant:" + position, Toast.LENGTH_SHORT).show();
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetpixels) {
}
// Called when the scroll state changes:
//SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
You should set different class in getItem(int position) section.
Return the Fragment associated with a specified position.
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //Fragment # 0 - This will show DevelopersFragment
return DescriptionFragment.newInstance(0, "page # 0");
case 1: //Fragment # 0 - This will show Page1Fragment
return Page1Fragment.newInstance(1, "Chant # Page1");
case 2: //Fragment # 0 - This will show Page1Fragment
return Page2Fragment.newInstance(2, "Chant # Page2");
case 3: //Fragment # 0 - This will show Page1Fragment
return Page3Fragment.newInstance(3, "Chant # Page2");
//etc
default:
return null;
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if (getFragmentManager() != null) {
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
}
Use this function in your Fragments, this function will attach the same fragment again on activity, and then fragment life cycle will start again. and then you can set image in respective fragment.
Related
I have never seen a bug as weird as that before, I'm linking a viewpager with a tablayout, inside the viewpager there are three fragments.
Two of the fragments (let's say fragment 1 & 3) have a button inside them and their colours are both set to "pink". When I first load the app, it shows fragment 1, the button is pink at that moment, however, whenever I switch to fragment 3, the background color of the button is changed to "white" and other attributes of the button stay the same.
This won't happen if I switch to fragment 2. However, if I switch to fragment 3 once, both fragments 1 & 3's button have white background for the rest of the lifetime.
Can someone tell me what's happening here or what could cause this? I'm not changing the style of the buttons in Java files at all.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setUpWithViewPager(binding.viewPager);
// setupWithViewPager is a built-in method for TabLayout, setting up this TabLayout with a ViewPager
// The TabLayout will be automatically populated from the PagerAdapter's page titles. By doing that,
// when the user tabs on the tab, the appropriate fragment will be shown in the ViewPager
// TabLayout provides a horizontal layout to display tabs.
// Without this line you can still swipe left/right to see all the pages, just cannot tab on the
// tab to switch pages
binding.tabLayout.setupWithViewPager(binding.viewPager);
// This method sets the toolbar as the app bar for the activity
setSupportActionBar(binding.toolbar);
// change the fab icon when the page is changed
binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
changeFabIcon(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setUpWithViewPager(ViewPager viewPager) {
// An inner class defined in MainActivity
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ChatsFragment(), "Chats");
adapter.addFragment(new StatusFragment(), "Status");
adapter.addFragment(new CallsFragment(), "Calls");
// We need 3 fragments
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater is used to instantiate menu XML files into Menu objects.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search: Toast.makeText(this, "Action Search", Toast.LENGTH_SHORT).show(); break;
case R.id.menu_more: Toast.makeText(this, "Action More", Toast.LENGTH_SHORT).show(); break;
}
return super.onOptionsItemSelected(item);
}
private void changeFabIcon(final int index) {
binding.fabAction.hide();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (index) {
case 0: binding.fabAction.setImageDrawable(getDrawable(R.drawable.ic_baseline_chat_24)); break;
case 1: binding.fabAction.setImageDrawable(getDrawable(R.drawable.ic_baseline_camera_alt_24)); break;
case 2: binding.fabAction.setImageDrawable(getDrawable(R.drawable.ic_baseline_call_24)); break;
}
binding.fabAction.show();
}
}, 400);
}
private static class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public SectionsPagerAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout
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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".view.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
app:titleTextColor="#android:color/white"
app:title="PepperChat"/>
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_below="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="50dp"
app:tabBackground="#color/colorPrimary"
app:tabGravity="fill"
app:tabIndicator="#color/colorPrimary"
app:tabIndicatorHeight="3dp"
app:tabIndicatorColor="#android:color/white"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#android:color/white">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_below="#id/tab_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_action"
android:src="#android:drawable/stat_notify_chat"
android:tint="#android:color/white"
app:backgroundTint="#color/colorPrimary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_margin="15dp"/>
</RelativeLayout>
</layout>
fragment_calls.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".menu.CallsFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<LinearLayout
android:id="#+id/ln_invite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Invite your friends"
android:textSize="25dp"
android:textColor="#android:color/black"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:textColor="#color/colorPrimary"
android:gravity="center_horizontal"
android:text="Name of your contact are using PepperChat.\nUse the bottom below to invite them."/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/black"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:text="Invite a friend"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:text="Chat with your friends who are using PepperChat on iphone,\nAndroid or KaiOS phone"/>
</LinearLayout>
</FrameLayout>
</layout>
fragment_chats.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".menu.ChatsFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
<LinearLayout
android:id="#+id/ln_invite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Invite your friends"
android:textSize="25dp"
android:textColor="#android:color/black"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:textColor="#color/colorPrimary"
android:gravity="center_horizontal"
android:text="Name of your contact are using PepperChat.\nUse the bottom below to invite them."/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#android:color/black"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:text="Invite a friend"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:text="Chat with your friends who are using PepperChat on iphone,\nAndroid or KaiOS phone"/>
</LinearLayout>
</FrameLayout>
</layout>
After adding the following line in both of the xml files, the button appears normally, not sure why though, can someone explain what happened? (is that something related to the theme I'm using?)
android:backgroundTint="#color/colorPrimary"
and my theme is
<style name="Theme.PepperChat" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
if I change the parent to Theme.MaterialComponent.Light.NoActionBar, then the app works fine without adding backgroundTint.
Again, would like some explanations on why this happens.
I am trying to show 4 fragments in one only ViewPager but when I scroll between Fragments the second fragment is not showing at all. It only shows Fragment 1,3 and 4 correctly.
I have checked a lot of other answers about stuff like this and they suggest to use
getChildFragmentManager()
instead of
getSupportFragmentManager()
and seems to work but, I can't use that because I'm using androidx.
This is my code in my MainActivity class:
public class MainMenu extends AppCompatActivity {
private ViewPager mViewPager;
private SectionPagerAdapter sectionPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
mViewPager = findViewById(R.id.menu_viewPager);
sectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager(),this, getFragmentList());
bottomNavigationView.setOnNavigationItemSelectedListener(this);
mViewPager.setAdapter(sectionPagerAdapter);
}
private List<Fragment> getFragmentList() {
List<Fragment> fragmentList = new ArrayList<>();
fragmentList.add(new HomeMenuFragment(this));
fragmentList.add(new RestaurantsListFragment(this));
fragmentList.add(new OrdersMenuFragment(this));
fragmentList.add(new AccountConfigurationFragment(this));
return fragmentList;
}
And this is my Adapter class for ViewPager:
public class SectionPagerAdapter extends FragmentStatePagerAdapter {
Context context;
private List<Fragment> fragments = new ArrayList<>();
public SectionPagerAdapter(FragmentManager fm, Context context, List<Fragment> fragments) {
super(fm);
this.context=context;
this.fragments=fragments;
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
case 3:
return "SECTION 4";
}
return null;
}
}
This is the my XML file for the first Fragment (HomeMenuFragment):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="#color/grayLight2"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_collapseMode="parallax"
android:background="#color/grayLight2"
>
<androidx.viewpager.widget.ViewPager
android:id="#+id/banner_view_pager"
android:layout_width="match_parent"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp"
android:layout_marginTop="10dp"
android:layout_height="150dp"
android:overScrollMode="never"/>
<LinearLayout
android:id="#+id/slider_dots"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal"/>
</LinearLayout>
<androidx.appcompat.widget.Toolbar
android:id="#+id/anim_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/food_recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</LinearLayout>
</LinearLayout>
I realize that what is causing this problem is what I have in my first Fragment's XML file:
CoordinatorLayout
AppBarLayout
CollapsingToolbarLayout
Toolbar
If I remove this elements the ViewPager displays all fragments correctly!
Any idea of what could I be doing wrong or what am I missing?
Thanks in advance!
In your SectionPagerAdapter class add break in the case statements and try
Like a lot of other people on the stackoverflow, for example:
https://ru.stackoverflow.com/questions/571704/%D0%A0%D0%B0%D0%B7%D0%BD%D1%8B%D0%B9-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82-%D0%BD%D0%B0-%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0%D1%85-viewpager
I'm trying to create ViewPager with different layouts, but with:
https://github.com/ogaclejapan/SmartTabLayout
Expectation: beautiful ViewPager with 3 tabs, which can switch different layouts/fragments by clicking on the buttons or by swipe.
Reality: beautiful ViewPager with 3 tabs, which are doing nothing.
Looking for your help, thanks.
What I have done in MainActivity class:
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setElevation(0); //toolbar shadow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ViewGroup tab = findViewById(R.id.linear_test);
tab.addView(LayoutInflater.from(this).inflate(R.layout.activity_main, tab, false));
ViewPager viewPager = findViewById(R.id.viewpager);
SmartTabLayout viewPagerTab = findViewById(R.id.viewpagertab);
setup(viewPagerTab);
FragmentPagerItems pages = new FragmentPagerItems(this);
pages.add(FragmentPagerItem.of("Вкладка 1", DemoFragment.class));
pages.add(FragmentPagerItem.of("Вкладка 2", DemoFragment.class));
pages.add(FragmentPagerItem.of("Вкладка 3", DemoFragment.class));
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(), pages);
viewPager.setAdapter(adapter);
viewPagerTab.setViewPager(viewPager);
}
public void setup(final SmartTabLayout layout) {
//Do nothing.
}
}
What I have done in my DemoFragment:
public class DemoFragment extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
private int page;
static DemoFragment newInstance(int page) {
DemoFragment pageFragment = new DemoFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.activity_main, container, false);
page = getArguments().getInt("someInt", 0);
return inflater.inflate(R.layout.activity_main, container, false);
// return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int position = FragmentPagerItem.getPosition(getArguments());
getItem(position);
}
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return DemoFragment.newInstance(1);
case 1: // Fragment # 0 - This will show FirstFragment different title
return DemoFragment.newInstance(2);
case 2: // Fragment # 1 - This will show SecondFragment
return DemoFragment.newInstance(3);
default:
return null;
}
}
}
Here is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<LinearLayout
android:id="#+id/linear_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"
android:background="#color/colorPrimary"
android:orientation="horizontal" >
<com.ogaclejapan.smarttablayout.SmartTabLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewpagertab"
android:layout_width="match_parent"
android:layout_height="#dimen/tab_height_large"
app:stl_customTabTextLayoutId="#layout/test_layout"
app:stl_customTabTextViewId="#id/custom_tab_text"
app:stl_distributeEvenly="true"
app:stl_defaultTabTextAllCaps="false"
app:stl_indicatorInterpolation="linear"
app:stl_defaultTabTextColor="#color/white"
app:stl_indicatorColor="#color/colorBlue"
app:stl_underlineColor="#color/colorBlue"
app:stl_defaultTabBackground="#color/colorPrimary"
app:stl_indicatorThickness="3dp"
app:stl_underlineThickness="1dp"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/viewpagertab"
/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/playlist_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linear_test" />
<TextView
android:id="#+id/dl_params"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:visibility="gone"
android:layout_weight="1"
tools:ignore="MissingConstraints"/>
</android.support.constraint.ConstraintLayout>
And finally test_layout which one is filling those SmartTabLayout:
<?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"
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
>
<android.support.v4.widget.Space
android:id="#+id/center_anchor"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerInParent="true"
/>
<aectann.pr1.TintableImageView
android:id="#+id/custom_tab_icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_above="#id/center_anchor"
android:layout_centerHorizontal="true"
android:scaleType="center"
android:src="#drawable/custom_icon"
/>
<TextView
android:id="#+id/custom_tab_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/center_anchor"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:maxLines="1"
android:textSize="14sp"
android:textColor="#color/white"
/>
</RelativeLayout>
Any ideas, guys?
I am using JakeWharton's ViewPagerIndicator on my landscape app but I think I am messing up with the layout. The ViewPagerIndicator does not show up. I just started learning Android Development so any help is appreciated!
My guess is that it has to do with my Linear Layout...should it be relative? Am I covering up the pager indicator? I know that if I move the indicator code above the view pager, I see the indicator but everything else is white. My fragment's layout is a relative layout with height and width matching the parent.
My app is an activity with fragments.
Edit: I set the indicator height to wrap content but now it floats on the top of the screen. How do I make it go down?
My_Activity.java
public class MyActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
MyPagerAdapter mAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(mAdapter);
CirclePageIndicator circleInd = (CirclePageIndicator) findViewById(R.id.circles);
circleInd.setViewPager(pager);
circleInd.setStrokeColor(0xAA000000);
//circleInd.setCurrentItem(mAdapter.getCount() - 1);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0: return FirstFragment.newInstance("First");
case 1: return SecondFragment.newInstance("Second");
default: return FirstFragment.newInstance("First");
}
}
#Override
public int getCount() {
return 2;
}
}
}
and the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.frontrowqa.myfirstapplication.MyActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/circles"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_gravity="bottom" />
</LinearLayout>
And my fragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<EditText
android:id="#+id/PasscodeText"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:hint="Passcode"
android:backgroundTint="#android:color/black" />
<EditText
android:id="#+id/ipAddressText"
android:layout_below="#id/PasscodeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="IP Address"
android:backgroundTint="#android:color/black" />
<EditText
android:id="#+id/intercomText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/ipAddressText"
android:hint="Intercom Event Number"
android:backgroundTint="#android:color/black"/>
<TextView
android:id="#+id/tvFragFirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="26dp"
android:text="TextView" />
</RelativeLayout>
Set your activity xml like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/circles"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:padding="10dp" />
</LinearLayout>
I have implemented a TabLayout which has a few tabs & one of the tabs has a table & when a user clicks on a row in the table I need it to get rid of the tab layout, except for the toolbar & open up a new Fragment.
I've tried a few different ways but nothing seems to work, if anyone has any ideas, it'll will be much appreciated!
Thank you!
Cheers!
This is the activity_main.xml
<RelativeLayout
android:id="#+id/main_layout"
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=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
& this is the MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
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) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
& this is tab1.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#F0F0F0" >
<ScrollView
android:id="#+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center" >
<TableLayout
android:id="#+id/table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
</TableLayout>
<RelativeLayout
android:id="#+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
</FrameLayout>
& this is Tab1.java
public class TopStories extends Fragment {
A lot of code goes here............
public void createTable() {
TableLayout table = (TableLayout) getActivity().findViewById(R.id.table);
table.setBackgroundColor(Color.rgb(240, 240, 240));
table.setStretchAllColumns(true);
table.setShrinkAllColumns(true);
table.removeAllViews();
TableRow row = new TableRow(getActivity());
row .setGravity(Gravity.CENTER);
row .setPadding(0, 10, 0, 10);
row .setBackgroundColor(Color.WHITE);
row .setClickable(true);
TableRow.LayoutParams params = new TableRow.LayoutParams();
row .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
This is where I need to start up the new fragment (NewFragment.Java).
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_topstories, container, false);
}
}
NewFragment.java
public class NewFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.newfragment, container, false);
}
}
newfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="18dp"/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_marginTop="87dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</LinearLayout>
I think you need to give the fragment somewhere to replace. Here is the XML from my app, and when I swap fragments, they post to flcontent.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk
xmlns:app="http://schemas.android.com/apk/res
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">
<!-- The ActionBar -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<!-- The main content view -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
</LinearLayout>
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
and the class code
// Insert the fragment by replacing any existing fragment
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.flContent, fragment);
ft.addToBackStack(null);
ft.commit();
Alright so I think that I figured out a really cheap & a cheeky way to do this & probably not very healthy for the app but it works perfect!
Thank you very much for the help Brian! Appreciate it! Maybe you can do this for the backstack problem of your app as well, don't know if it will work or the right thing that you need to do though.
Cheers!
Added a FrameLayout to my main_activity.xml
<RelativeLayout
android:id="#+id/main_layout"
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=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</RelativeLayout>
Changed my newfragment.xml to this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fullStoryLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/fullStoryRelativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="80dp"/>
<TextView
android:id="#+id/fullStorytitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/fullStory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/image"
android:layout_marginTop="50dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</LinearLayout>
& added this to the onClick event of the table row
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().findViewById(R.id.tab_layout).setVisibility(View.GONE);
getActivity().findViewById(R.id.pager).setVisibility(View.GONE);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("New Fragment");
Fragment fragment = null;
Class fragmentClass = NewFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContent, fragment);
fragmentTransaction.commit();
}
});
& to go back to the main TabLayout from the NewFragment, I added this at MainActivity.java
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode){
case KeyEvent.KEYCODE_BACK:
if (getSupportActionBar().getTitle() != "Main Activity"){
onBackPressed();
}
else {
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed(){
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle("Main Activity");
findViewById(R.id.fullStoryLinearLayout).setVisibility(View.GONE);
findViewById(R.id.tab_layout).setVisibility(View.VISIBLE);
findViewById(R.id.pager).setVisibility(View.VISIBLE);
}