My tablayout is working perfectly, tabs are switching right/left and displaying content correctly.
But when "Clicking" on the tabs, no action happens.
Question : How can I do to switch tabs with a onClick ? I tried to add an onClickListener on each tab but it's not working.
Here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<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>
Here is my Java
package com.example.alexis.tablayout;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(getResources().getText(R.string.MOD));
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
final TabLayout.Tab Manof = tabLayout.newTab();
final TabLayout.Tab Catalogue = tabLayout.newTab();
final TabLayout.Tab Lidory = tabLayout.newTab();
Manof.setIcon(R.drawable.flamepink);
Catalogue.setIcon(R.drawable.modwhite);
Lidory.setIcon(R.drawable.pantywhite);
tabLayout.addTab(Manof, 0);
tabLayout.addTab(Catalogue, 1);
tabLayout.addTab(Lidory, 2);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
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));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position){
case 0:
Manof.setIcon(R.drawable.flamepink);
Catalogue.setIcon(R.drawable.modwhite);
Lidory.setIcon(R.drawable.pantywhite);
setTitle("Man Of The Day");
break;
case 1:
Manof.setIcon(R.drawable.flamewhite);
Catalogue.setIcon(R.drawable.modpink);
Lidory.setIcon(R.drawable.pantywhite);
setTitle("Catalogue");
break;
case 2:
Manof.setIcon(R.drawable.flamewhite);
Catalogue.setIcon(R.drawable.modwhite);
Lidory.setIcon(R.drawable.pantypink);
setTitle("Lidory");
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#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.Menu) {
return true;
}
return super.onOptionsItemSelected(item);
}}
You should try to combine the TabLayout with the ViewPager;
tabLayout.setupWithViewPager(yourViewPager);
Also, make sure that the ViewPager does not overlay the TabLayout.
I had exactly the same problem. This worked for me:
First, create a listener class to receive the click event on a tab (source code is in Kotlin, but you can easily translate to Java). This class extends TabLayout.OnTabSelectedListener and needs a viewPager on its constructor.
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
class MyTabLayoutListener(viewPager: ViewPager):
TabLayout.OnTabSelectedListener {
val viewer = viewPager
override fun onTabReselected(tab: TabLayout.Tab?) {
//Empty but needed
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
//Empty but needed
}
override fun onTabSelected(tab: TabLayout.Tab?) {
viewer.setCurrentItem(tab!!.position) //When a tab is clicked, the item on viewPager is changed.
}
}
Now, create an instance of this listener and add it to your tab:
var listener : MyTabLayoutListener = MyTabLayoutListener(viewPager)
tabLayout.addOnTabSelectedListener(listener)
Related
I have used view pager and and Tablayout for tabbed activity.clicking on the tab is changing but the issue is that I unable to swap between the fragments, and the text in the fragment is not shown. Using tabLayout.setupWithViewPager(viewPager);is making my tab invisble
Here is my activity_main code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:minHeight="?attr/actionBarSize"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<TextView
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:paddingTop="10dp"
android:gravity="center_horizontal"
android:text="Sample ViewPager"
android:textColor="#color/colorPrimary"
android:textSize="20sp"
android:textStyle="bold"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"
/>
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#android:color/transparent"
android:minHeight="?attr/actionBarSize"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"
app:tabMode="scrollable"
app:tabTextColor="#color/colorPrimary">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viepager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
Here is the Main Activity:
package com.example.sidrajawaid.demoviewpager;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements tab1.OnFragmentInteractionListener,tab2.OnFragmentInteractionListener,tab3.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager viewPager=findViewById(R.id.viepager);
TabLayout tabLayout=findViewById(R.id.tablayout);
PagerAdapter pagerAdapter=new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
tabLayout.addTab(tabLayout.newTab().setText("Log In"));
tabLayout.addTab(tabLayout.newTab().setText("RecyclerView"));
tabLayout.addTab(tabLayout.newTab().setText("Coordinator"));
tabLayout.addTab(tabLayout.newTab().setText("ListView"));
tabLayout.addTab(tabLayout.newTab().setText("Log In"));
tabLayout.addTab(tabLayout.newTab().setText("RecyclerView"));
tabLayout.addTab(tabLayout.newTab().setText("Coordinator"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager.setAdapter(pagerAdapter);
//tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(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 void onFragmentInteraction(Uri uri) {
}
}
Here is my Adapter class code:
package com.example.sidrajawaid.demoviewpager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PagerAdapter extends FragmentStatePagerAdapter {
int numberOfTabs;
public PagerAdapter(FragmentManager fm,int tabs) {
super(fm);
this.numberOfTabs=tabs;
}
#Override
public Fragment getItem(int position) {
{
switch (position){
case 0:
tab1 tab_1=new tab1();
return tab_1;
case 1:
tab2 tab_2=new tab2();
return tab_2;
case 2:
tab3 tab_3=new tab3();
return tab_3;
}
return null;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return super.getPageTitle(position);
}
#Override
public int getCount() {
return 0;
}
}
Here is tab1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".tab1">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/hello_blank_fragment" />
</RelativeLayout>
Solve my 2 problems:
1- Swapping between tabs.
2- Content not shown in fragments.
The issue is here
PagerAdapter pagerAdapter=new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
the second argument is 0 because no tabs are added yet. so cut above line and paste it above the
viewPager.setAdapter(pagerAdapter);
in onCreate() Method in your fragment and please check getCount() in adapter also. make sure it is returning the proper value.
I have 3 tabs and these tabs have recyclerview within swiperefreshlayout. I cannot change these tabs with swipe. I think this is because, my touch event is getting received by swiperefreshlayout instead of tablayout. How to solve my problem?
Following is my layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout 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/news_swipe_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.nabinkhadka.hamrodang.activity.NewsActivity"
tools:showIn="#layout/app_bar_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/news_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.v4.widget.SwipeRefreshLayout>
Problems:
If I move ViewPager above RecyclerView, then the swipe works but Recyclerview cannot be seen.
If I create a Relativelayout for these two and place each one above the other, I won't be able to make touch events on one of them
How can I get a work around?
Thank you!
You should change your layout design. Here is the solution:
Design a layout with TabLayout and ViewPager for your Activity.
Design another layout with SwipeRefrashLayout and RecyclerView for each TAB Fragment.
Finally, use FragmentPagerAdapter to populate Fragment's on ViewPager.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:layout_scrollFlags="scroll|enterAlways"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs_my_offers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
style="#style/MyCustomTabLayout"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager_my_offers"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
fragment_tab.xml
<?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"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
TabsPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class TabsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public TabsPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
MainActivity.java
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import company.screenshot.fundle.R;
import company.screenshot.fundle.points.adapter.TabsPagerAdapter;
public class MainActivity extends AppCompatActivity {
// TAG
private static final String TAG = MainActivity.class.getSimpleName();
Context mContext;
ViewPager mViewPager;
TabLayout mTabLayout;
TabsPagerAdapter mTabsPagerAdapter;
// ToolBar
Toolbar mToolBar;
// Actionbar
ActionBar mActionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Context
mContext = this;
// ToolBar
mToolBar = (Toolbar) findViewById(R.id.toolbar);
if(mToolBar != null)
{
setSupportActionBar(mToolBar);
mActionBar = getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setTitle("History");
}
// Status bar :: Transparent
Window window = this.getWindow();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
// Tabs
mTabLayout = (TabLayout) findViewById(R.id.tabs_my_offers);
mViewPager = (ViewPager) findViewById(R.id.view_pager_my_offers);
mTabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
mTabsPagerAdapter.addFrag(new FragmentEarnedHistories(), "EARNED");
mTabsPagerAdapter.addFrag(new FragmentRedeemedHistories(), "REDEEMED");
mViewPager.setAdapter(mTabsPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Hello I am currently working on a viewpage template using the following tutorial:
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
I was able to add a filter as well as changing color for each tab but I am running into a weird issue. The template with a fab and I added a feature that whenever the fab is pressed it will add and extra tab and reload the tablayout. This method works great. However, when I tilt the device horizontally the view goes back to being only one tab (how it was when the application opened.) Any ideas why this would happened? I tried a few things including finishing the activity and restarting it but no luck. Thank you in advance.
JAVA:
package com.example.reasults.materialpagerdesign;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.security.cert.CertificateParsingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import com.example.reasults.materialpagerdesign.OneFragment;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private LinkedList<String> tabs = new LinkedList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (tabs.size() < 1) { tabs.add("ONE");};
//if (tabs.size() == 2) {Log.i("TEST", "here");}
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
tabs.add("Two");
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
/*Log.i("TEST", Integer.toString(tabs.size()));
tabs.add("Two");
Log.i("TEST", Integer.toString(tabs.size()));
Intent intent = new Intent(MainActivity.this, MainActivity.class);
finish();
startActivity(intent);*/
}
});
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
tabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
if (position == 1) {
toolbar.setBackgroundColor(Color.parseColor("#4DAC26"));
tabLayout.setBackgroundColor(Color.parseColor("#4DAC26"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//adapter.addFragment(new OneFragment(), "ONE");
for (int i = 0; i < tabs.size(); i ++){
adapter.addFragment(new OneFragment(), tabs.get(i));
}
viewPager.setAdapter(adapter);
}
private void setupViewPager2(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "Two");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
how can we add goBack function in webview fragment?
when I click BACK button, it quits from fragment, I want it not to finish, but load the old website.
I tried ,this link but changed some words and it s not working...
please help.
code is here;
FRAGMENT ACTIVITY;
package info.androidhive.materialtabs.activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.webkit.WebView;
import android.webkit.WebViewFragment;
import java.util.ArrayList;
import java.util.List;
import info.androidhive.materialtabs.R;
import info.androidhive.materialtabs.fragments.OneFragment;
import info.androidhive.materialtabs.fragments.ThreeFragment;
import info.androidhive.materialtabs.fragments.TwoFragment;
public class SimpleTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
FRAGMENT LAYOUT;
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
Override the onBackPressed method from your Activity.
From there try to find your current fragment and call a method from this fragment that will handle your web views action
Example (This code belongs to your Activity):
#Override
public void onBackPressed() {
if (getFragmentManager().findFragmentById(R.id.container) instanceof YourFragment) {
YourFragment currentFragment = (YourFragment) getFragmentManager().findFragmentById(R.id.container);
if (currentFragment != null) {
currentFragment.handleWebViewNavigation();
}
}
}
Actually you can not do directly inside the fragment. The onBackPressed can be overridden in the FragmentActivity. What you can do is:
Override the onBackPressed inside the activity.
When the onBackPressed is called, check if the instance of the current fragment is the instance showing the webview.
If it is, ask the fragment if the webview can go back.
if it is not, call the super or whatever you need
for more detail visit this How to add "Go Back" function in WebView inside Fragment?
i'm working on some app with viewpager and its fragments.the problem is that back button doesnt work when its used to close the app.but in other cases it works.is there any wrong code here or a trick to close the app.
edit:I even overrided onbackpressed method and just put a toast message in it instead of finish(); but again the toast message didnt appear.
this is my main activity:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
public class MaxMainActivity extends AppCompatActivity {
private final int numOfPages = 3; //viewpager has 4 pages
private final String[] pageTitle = {"STUDY", "MENU", "QUIZ"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_max_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
for (int i = 0; i < numOfPages; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), numOfPages);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_max_main, menu);
return true;
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
}
And this is main layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimaryDark"
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:minHeight="?attr/actionBarSize"
style="#style/MyCustomTabLayout"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tab_layout" />
</RelativeLayout>
edit:
some where i read this problem is common for old api's working with new L affairs.whats your idea?
You should not override onBackPressed, read in docs:
Take care of popping the fragment back stack or finishing the activity
as appropriate.
It is true app is not getting killed immediately, OS takes care about such stuff.
you dont need to override the onBackPressed() remove the override
then override the onStop and call onBackPressed from inside of it
read something about android lifecycle you will get it
#Override
protected void onStop(Bundle savedInstanceState){
super.onStop(savedInstanceState);
onBackPressed();
}
Give it a try tell me if it works