I have an application. I use in Main activity tab layout with view pager. I tried to load a fragment in every 3 tab in my view pager.but my fragment does not show in view pager.I did it before several times but now it does not work!!
I dont know where is my mistake.
mainactivity.java:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ImageView hamgerMenu;
DrawerLayout drawer;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setupviews();
}
private void setupviews() {
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragments(new FragmentFriends(), "فعالیت ها");
adapter.addFragments(new FragmentFriends(), "فعالیت ها");
adapter.addFragments(new FragmentFriends(), "فعالیت ها");
adapter.addFragments(new FragmentFriends(), "فعالیت ها");
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(2);
tabLayout.setupWithViewPager(viewPager);
hamgerMenu = (ImageView) findViewById(R.id.img_mainactivity_hambermenu);
hamgerMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(Gravity.RIGHT);
}
});
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(Gravity.RIGHT);
return true;
}
}
viewpagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments;
ArrayList<String> titles;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
fragments=new ArrayList<>();
titles=new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
public void addFragments(Fragment fragment,String title){
fragments.add(fragment);
titles.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
fragment:
public class FragmentFriends extends Fragment {
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
inflater.inflate(R.layout.friends_fragment,container,false);
return view;
}
}
mainactivity.xml:
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layoutDirection="rtl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layoutDirection="rtl"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
appbarmain.xml:
<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:layoutDirection="rtl"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layoutDirection="rtl"
android:elevation="0dp"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<RelativeLayout
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layoutDirection="rtl">
<ImageView
android:id="#+id/img_mainactivity_hambermenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:src="#drawable/ic_hambermenu" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="18dp" />
</RelativeLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:background="#color/colorPrimary"
app:tabIndicatorColor="#color/white"
app:tabSelectedTextColor="#color/colorAccent"
app:tabTextColor="#color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<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"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
contentmain.xml:
<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:orientation="vertical"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/app_bar_main">
<android.support.v4.view.ViewPager
android:layoutDirection="ltr"
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
just make this change it will work
view = inflater.inflate(R.layout.friends_fragment,container,false);
Related
I have a problem while developing an android app, I have created a default view in DrawerLayout nesting recyclerview but the view stuck after when the the app is getting json from the server while the view with data are showing below it.
Below are the code I have included for mainactivity.xml content.xml, adapter.java class and mainactivity.java class
Mainactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/customeView"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.design.widget.CoordinatorLayout>
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>``
content.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="11dp"
android:layout_marginRight="11dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="7dp"
app:cardCornerRadius="10dp">
<RelativeLayout
android:background="?android:attr/selectableItemBackground"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:transitionName="img"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
tools:ignore="UnusedAttribute" />
<ImageView
android:id="#+id/shadow_bottom"
android:src="#drawable/bottom_shadow"
android:layout_alignBottom="#id/image"
android:layout_width="match_parent"
android:layout_height="80dp" />
<FrameLayout
android:id="#+id/layoutDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/image"
android:background="#drawable/round_white"
android:padding="5dp"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
android:layout_marginTop="-50dp">
<ImageView
android:src="#drawable/ic_date"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
<TextView
android:textColor="#606060"
android:id="#+id/publishedAt"
android:layout_marginLeft="27dp"
android:layout_marginRight="10dp"
android:text="01 January 1990"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:textStyle="bold"
android:textColor="#color/colorTextTitle"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="Title"
android:textSize="17sp"
android:layout_marginTop="10dp"
android:layout_below="#id/image"
android:id="#+id/title" />
<TextView
android:id="#+id/txtContents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="5dp"
android:text="Desc"
/>
<TextView
android:id="#+id/source"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_below="#id/txtContents"
android:layout_marginTop="10dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="10dp"
android:fontFamily="sans-serif-light"
android:textStyle="bold"
android:textColor="#color/colorTextTitle"
android:maxLines="1"
android:drawablePadding="10dp"
android:singleLine="true"
android:ellipsize="end"
android:text="Source" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</FrameLayout>``
Adapter.java
``public class Adapter extends
RecyclerView.Adapter<Adapter.AdapterViewHolder> {
private List<Articles> dataList;
private Context context;
private String storage_url="http://192.168.56.1/muslimnews/storage/";
public Adapter(Context context,List<Articles> dataList){
this.context = context;
this.dataList = dataList;
}
class AdapterViewHolder extends RecyclerView.ViewHolder {
public final View mView;
TextView txtTitle;
TextView txtContents;
TextView source;
TextView date;
private ImageView coverImage;
AdapterViewHolder(View itemView) {
super(itemView);
mView = itemView;
txtTitle = mView.findViewById(R.id.title);
txtContents=mView.findViewById(R.id.txtContents);
coverImage = mView.findViewById(R.id.image);
source=mView.findViewById(R.id.source);
date=mView.findViewById(R.id.publishedAt);
}
}
#NonNull
#Override
public AdapterViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.content_main,parent,false);
return new AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AdapterViewHolder holder, int position) {
holder.txtTitle.setText(dataList.get(position).getTitle());
holder.txtContents.setText(Html.fromHtml(dataList.get(position).getShort_content()));
holder.source.setText(dataList.get(position).getSource());
try {
Date date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dataList.get(position).getCreated_at());
String publishedDate=new SimpleDateFormat("dd MMMM yyyy").format(date);
holder.date.setText(publishedDate);
} catch (ParseException e) {
e.printStackTrace();
}
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(new OkHttp3Downloader(context));
builder.build().load(storage_url+dataList.get(position).getImgUrl())
.placeholder((R.drawable.ic_launcher_background))
.error(R.drawable.ic_launcher_background)
.into(holder.coverImage);
}
#Override
public int getItemCount() {
return dataList==null ? 0: dataList.size();
}
}``
mainactivity.java
`public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
SwipeRefreshLayout.OnRefreshListener {
private Adapter adapter;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataService service= RetrofitClientInstance.getRetrofitInstance()
.create(GetDataService.class);
Call<List<Articles>> call=service.getAllArticles();
call.enqueue(new Callback<List<Articles>>() {
#Override
public void onResponse(Call<List<Articles>> call, Response<List<Articles>> response) {
recyclerView=findViewById(R.id.customeView);
adapter=new Adapter(MainActivity.this,response.body());
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setAdapter(adapter);
//generateDataList(response.body());
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<List<Articles>> call, Throwable t) {
Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_LONG).show();
}
});
swipeRefresh();
createMenu();
}
private void swipeRefresh(){
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
}
private void createMenu(){
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void fillMain(){
GetDataService service= RetrofitClientInstance.getRetrofitInstance()
.create(GetDataService.class);
Call<List<Articles>> call=service.getAllArticles();
call.enqueue(new Callback<List<Articles>>() {
#Override
public void onResponse(Call<List<Articles>> call, Response<List<Articles>> response) {
swipeRefreshLayout.setRefreshing(false);
generateDataList(response.body());
}
#Override
public void onFailure(Call<List<Articles>> call, Throwable t) {
swipeRefreshLayout.setRefreshing(true);
Toast.makeText(MainActivity.this,"Something went wrong",Toast.LENGTH_LONG).show();
}
});
}
private void generateDataList(List<Articles> articlesList){
recyclerView=findViewById(R.id.customeView);
adapter=new Adapter(this,articlesList);
adapter.notifyDataSetChanged();
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
// recyclerView.setItemAnimator(new DefaultItemAnimator());
// recyclerView.setNestedScrollingEnabled(false);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onRefresh() {
fillMain();
}
}`
set your manifest theme to Appcomat.theme.nocationbar and put custom toolbar or actionbar in activity.
<application
android:name="androidx.multidex.MultiDexApplication"
android:allowBackup="true"
android:appComponentFactory="whateverString"
android:debuggable="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:testOnly="false"
android:theme="#style/AppTheme" //here you can edit it. completly.
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning,HardcodedDebugMode"
tools:replace="android:appComponentFactory"
tools:targetApi="m">
I need some help with my android application. The problem I had faced is that I had created Base activity, that controls Drawer Layout and toolbar. When I am extending it in activity for Relative Layout and nested Recycle View, I get a problem that a can't scroll it (But, when activity is starting, I can catch the moment and do it, but one time). Another situation - I opened an application without extending Base activity in my activity for RecycleView and it works okay.
RecyclerView:
<?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=".EntryList"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/entry_list">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:padding="4dp"
android:scrollbars="vertical"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
</RelativeLayout>
Main activity (Drawer):
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
AppBar included to Drawer:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/coordinator_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorWhite"
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="#drawable/gradient_color"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<FrameLayout
android:id="#+id/activity_content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
Base Activity:
public abstract class BaseActivity extends AppCompatActivity {
protected Context context;
protected Toolbar toolbar;
private DrawerLayout drawer;
private ProgressBar loadingProgressBar;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
context = BaseActivity.this;
setContentView(R.layout.activity_main);
}
#Override
public void setContentView(int layoutResID) {
DrawerLayout fullView = (DrawerLayout)getLayoutInflater().inflate(R.layout.activity_main, null);
FrameLayout activityContainer = fullView.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
super.setContentView(fullView);
initToolBar();
}
private void initToolBar() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setUpNavigation();
toggle.syncState();
}
private void setUpNavigation() {
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(BaseActivity.this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
ActionBar actionBar = getSupportActionBar();
if (actionBar == null) {
throw new NullPointerException("ActionBar is null");
}
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
drawer.closeDrawers();
Intent intent;
switch (item.getItemId()) {
case R.id.nav_home:
intent = new Intent(BaseActivity.this, EntryList.class);
startActivity(intent);
return true;
}
return false;
}
});
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item))
return true;
// 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);
}
Adapter:
public class EntryListAdapter extends RecyclerView.Adapter<EntryListAdapter.EntryListViewHolder> {
private List<ExampleEntryItem> items;
public static class EntryListViewHolder extends RecyclerView.ViewHolder {
private TextView specieNameRuTextView;
private TextView entryDateTextView;
private TextView specieNameLatTextView;
private TextView entryPlaceTextView;
public EntryListViewHolder(#NonNull View itemView) {
super(itemView);
specieNameRuTextView = itemView.findViewById(R.id.specie_name_ru);
entryDateTextView = itemView.findViewById(R.id.entry_date);
specieNameLatTextView = itemView.findViewById(R.id.specie_name_lat);
entryPlaceTextView = itemView.findViewById(R.id.entry_place);
}
}
public EntryListAdapter(List<ExampleEntryItem> items) {
this.items = items;
}
#NonNull
#Override
public EntryListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_entry_item, parent, false);
return new EntryListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull EntryListViewHolder entryListViewHolder, int position) {
ExampleEntryItem item = this.items.get(position); // TODO: 06.05.2019 test for null
entryListViewHolder.entryPlaceTextView.setText(item.getEntryPlace());
entryListViewHolder.entryDateTextView.setText(item.getEntryDate());
entryListViewHolder.specieNameRuTextView.setText(item.getSpecieNameRu());
entryListViewHolder.specieNameLatTextView.setText(item.getSpecieNameLat());
}
#Override
public int getItemCount() {
return this.items.size();
}
RecycleView control class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entry_list_content_main);
List<ExampleEntryItem> items = new ArrayList<>();
adding items...
RecyclerView recyclerView = findViewById(R.id.recycler_view);
RecyclerView.Adapter adapter = new EntryListAdapter(items);
adapter.notifyDataSetChanged();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
Thanks, everybody, who will help me
You first need to remove
adapter.notifyDataSetChanged()
After this if you use recycler view inside nested scrolling
You need to add a single line
recyclerView.setNestwdScrollingenable(false)
I resolved the problem. I replace my logic for recyclerview in frament, and mainly change, that I do is - in layout with appbar, I replaced <include layout="#layout/content"/> to outside of AppBarLayout and change line:
android:layout_height="match_parent"
android:background="#color/colorWhite"
to this:
android:layout_height="wrap_content"
This is my activity_main code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:layoutDirection="rtl"
tools:context=".MainActivity"
tools:openDrawer="start">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:paddingTop="#dimen/appbar_padding_top"
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"
android:layoutDirection="rtl"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="rtl" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<com.duolingo.open.rtlviewpager.RtlViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="rtl"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layoutDirection="rtl"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>
I want to add some fragments to ViewPager in NestedScrollView.
Without adding fragments to ViewPager everything is ok and I can exit from app by device back button, but when I am adding fragment(s) to ViewPager I can not exit from app by pressing device back button.(Back button is working and for example can close soft keyboard)
this is my fragment code:
(empty fragment!)
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_jadvalyab,container,false);
}
and this is my adapter:
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentsList = new ArrayList<>();
private ArrayList<String> fragsTitleList = new ArrayList<>();
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment,String title){
fragmentsList.add(fragment);
fragsTitleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragsTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return fragmentsList.get(position);
}
#Override
public int getCount() {
return fragmentsList.size();
}
}
Does anyone have an idea to solving this problem?
Thanks.
Edit:
Problem solved by removing NestedScrollingView from coordinator layout in activity_main and putting that in fragment layout (inside viewpager).
But still I don't know why device back button did not worked in former state.
I think the problem is occurring because you have used a third party library for ViewPager.
Just copy and paste the following code in the place of your "activity_main.xml" file.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<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"
tools:context=".Main2Activity">
<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" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main2" />
<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"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>
I have initialized fragment to ViewPager like this
ViewPager viewPager2 = findViewById(R.id.viewpager);
MyFragmentPagerAdapter pagerAdapter2 = new MyFragmentPagerAdapter(getSupportFragmentManager());
pagerAdapter2.addFragment(TestFragment.createInstance(),"Home");
viewPager2.setAdapter(pagerAdapter2);
TabLayout tabLayout2 = findViewById(R.id.tabs);
tabLayout2.setupWithViewPager(viewPager2);
Here is the Testfragment.java class
public class TestFragment extends Fragment {
public static TestFragment createInstance() {
TestFragment profileFragment = new TestFragment();
return profileFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jadvalyab, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
}
And the full code of "Main2Activity.java" class is here
public class Main2Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
initViewPager();
}
private void initViewPager() {
ViewPager viewPager2 = findViewById(R.id.viewpager);
MyFragmentPagerAdapter pagerAdapter2 = new MyFragmentPagerAdapter(getSupportFragmentManager());
pagerAdapter2.addFragment(TestFragment.createInstance(),"Home");
viewPager2.setAdapter(pagerAdapter2);
TabLayout tabLayout2 = findViewById(R.id.tabs);
tabLayout2.setupWithViewPager(viewPager2);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Edit:
Code of "content_main2.xml"
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.v4.widget.NestedScrollView>
Code for "fragment_jadvalyab.xml" is in te following
<?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">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Best Wishes"
android:gravity="center"/>
</LinearLayout>
Try this
#Override
public void onBackPressed() {
//Your Action
}
Override onBackPress(){} event in your MainActivity which holds your above xml layout.
#Override
public void onBackPressed() {
finish();
}
override OnBackPressed() method , or you can write your adapter as this.
public class Adapter extends FragmentStatePagerAdapter {
public Adapter (FragmentManager fm) {
super(fm);
}
// you can add fragments according to your requirement
#Override
public Fragment getItem(int position) {
Fragment fragment= null;
switch (position){
case 0:
fragment= new fragmentDay();
break;
case 1:
fragment= new fragmentWeek();
break;
case 2:
fragment= new fragmentMonth();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
and inside activity pass fragment manager to adapter constructor.
fragmentManager= getSupportFragmentManager();
adapter= new Adapter(fragmentManager);
viewPager.setAdapter(adapter);
I have used tablayout with viewpager
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabsFromPagerAdapter(adapter);
tabLayout.getTabAt(0).setText("Day");
tabLayout.getTabAt(1).setText("Week");
tabLayout.getTabAt(2).setText("Month");
tabLayout.getTabAt(1).select();
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
I've created my application with Navigation Drawer. In my Activity I put this code:
public class MenuActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
{
public void onDrawerOpened(View view)
{
super.onDrawerOpened(view);
}
public void onDrawerClosed(View v)
{
super.onDrawerClosed(v);
}
};
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
onNavigationItemSelected(navigationView.getMenu().getItem(0));
navigationView.setNavigationItemSelectedListener(this);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
String title = null;
int id = item.getItemId();
Class fragmentClass=null;
if (id == R.id.Home)
{
fragmentClass = HomeFragment.class;
title="Home";
}
else if (id == R.id.Profile)
{
fragmentClass= ProfileFragment.class;
title="Profile";
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
if (getSupportActionBar() != null)
{
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
now in the HomeFragment I want to put a tab in the bottom of the screen. So i put this code:
public class HomeFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.fragment_home, null);
tabLayout = (TabLayout) inflatedView.findViewById(R.id.tabs);
viewPager = (ViewPager) inflatedView.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return inflatedView;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new SearchFragment();
case 1 : return new CardFragment();
case 2 : return new MapFragment();
}
return null;
}
public int getCount() {
return int_items;
}
This is fragment_home.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".HomeFragment">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/material_blue_grey_800"
app:tabIndicatorColor="#color/black_overlay"
app:tabSelectedTextColor="#000"
app:tabTextColor="#FFFFFF"
android:layout_gravity="bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>
</FrameLayout>
and this the activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_menu"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/containerView">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu"
app:menu="#menu/activity_menu_drawer" />
</android.support.v4.widget.DrawerLayout>
But finally I get this result:
How could I put this tabLayout in the toolbar?
You don't need to take frame layout for fragment_home as root layout. Simplify your xml file as:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="#color/material_blue_grey_800"
app:tabIndicatorColor="#color/black_overlay"
app:tabSelectedTextColor="#000"
app:tabTextColor="#FFFFFF"
android:layout_gravity="bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>
I Experimented a bit in viewPager.
One viewpager with different FragmentAdapter.
For now the code works perfectly but I don't know if its the right way to do that.
For my Activity is this.
public class Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, View.OnClickListener {
private DrawerLayout drawer;
private ViewPager pager;
public static TabHost tabHost;
public static TabWidget tabWidget;
public static FloatingActionMenu fab;
private boolean doubleBackToExitPressedOnce = false;
private String currentTab;
private Button mButton;
private LinearLayout mLinearLayout;
private PagerSlidingTabStrip mTabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().getAttributes().windowAnimations = 0;
setContentView(R.layout.activity_navigation);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
fab = (FloatingActionMenu) findViewById(R.id.fabMenu);
fab.setVisibility(View.GONE);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
tabHost.setOnTabChangedListener(this);
tabWidget = (TabWidget) findViewById(android.R.id.tabs);
setNewTab(tabHost, "tab1", R.string.textTabTitle1, R.drawable.icon_search, R.id.tab1);
setNewTab(tabHost, "tab2", R.string.textTabTitle1, R.drawable.icon_comment, R.id.tab2);
setNewTab(tabHost, "tab3", R.string.textTabTitle1, R.drawable.icon_car, R.id.tab3);
mTabLayout = (PagerSlidingTabStrip) findViewById(R.id.tab);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new FragmentAdapterSearch(getSupportFragmentManager()));
mTabLayout.setViewPager(pager);
pager.addOnPageChangeListener(this);
mButton = (Button) findViewById(R.id.btnSearch);
mLinearLayout = (LinearLayout) findViewById(R.id.btnSelectLocation);
mButton.setOnClickListener(this);
mLinearLayout.setOnClickListener(this);
TabIcon.setColor(0, mTabLayout, iconSearchOpac, iconSearch);
}
private void setNewTab(TabHost tabHost, String tag, int title, int icon, int contentID) {
TabHost.TabSpec tabSpec = tabHost.newTabSpec(tag);
tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), title, icon));
tabSpec.setContent(contentID);
tabHost.addTab(tabSpec);
}
private View getTabIndicator(Context context, int title, int icon) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
final ImageView iv = (ImageView) view.findViewById(R.id.imageView);
iv.setImageResource(icon);
TextView tv = (TextView) view.findViewById(R.id.textView);
tv.setText(title);
return view;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (!drawer.isDrawerOpen(GravityCompat.START)) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tap Again to Exit Toweelo", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (drawer.isDrawerOpen(Gravity.LEFT)) {
drawer.closeDrawer(Gravity.LEFT);
} else {
drawer.openDrawer(Gravity.LEFT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabId;
if (currentTab.equalsIgnoreCase("tab1")) {
if (pager != null) {
pager.setAdapter(new FragmentAdapterSearch(getSupportFragmentManager()));
mButton.setVisibility(View.VISIBLE);
TabIcon.setColor(0, mTabLayout, iconSearchOpac, iconSearch);
}
}
if (currentTab.equalsIgnoreCase("tab2")) {
if (pager != null) {
pager.setAdapter(new FragmentAdapterComments(getSupportFragmentManager()));
mButton.setVisibility(View.INVISIBLE);
TabIcon.setColor(0, mTabLayout, iconCommentOpac, iconComment);
}
}
if (currentTab.equalsIgnoreCase("tab3")) {
if (pager != null) {
pager.setAdapter(new FragmentAdapterCars(getSupportFragmentManager()));
mButton.setVisibility(View.VISIBLE);
TabIcon.setColor(0, mTabLayout, iconCarOpac, iconCar);
}
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (currentTab.equalsIgnoreCase("tab1")) {
TabIcon.setColor(position, mTabLayout, iconSearchOpac, iconSearch);
}
if (currentTab.equalsIgnoreCase("tab2")) {
TabIcon.setColor(position, mTabLayout, iconCommentOpac, iconComment);
}
if (currentTab.equalsIgnoreCase("tab3")) {
TabIcon.setColor(position, mTabLayout, iconCarOpac, iconCar);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch:
startActivity(new Intent(Navigation.this, SelectCategory.class));
break;
case R.id.btnSelectLocation:
startActivity(new Intent(Navigation.this, SelectLocation.class));
}
}
}
And for my XML is this.
<?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:fab="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:background="#color/colorWhite"
android:fitsSystemWindows="true"
tools:context="com.toweelo.Navigation">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<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"
>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:weightSum="10">
<LinearLayout android:id="#+id/btnSelectLocation"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5.5"
android:background="#drawable/ripple_effect"
android:clickable="true"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:paddingLeft="8dp">
<com.toweelo.custom.CustomTextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Quezon City"
android:textColor="#color/colorWhite"
android:textSize="#dimen/title"/>
<ImageView
android:layout_width="24dp"
android:layout_height="match_parent"
android:src="#drawable/ic_down_arrow"/>
</LinearLayout>
<RelativeLayout android:layout_width="0dp"
android:layout_height="36dp"
android:layout_marginLeft="10dp"
android:layout_weight="4.5">
<Button android:id="#+id/btnSearch"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/custom_search_button"
android:drawableRight="#drawable/ic_search"
android:text="Search"
android:textColor="#color/colorWhite"
android:textSize="14dp"/>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.Toolbar>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#color/colorPrimary"
app:pstsDividerColor="#color/colorPrimary"
app:pstsIndicatorColor="#color/colorWhite"
app:pstsIndicatorHeight="3dp"
app:pstsShouldExpand="true"
app:pstsTextAllCaps="false"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
<com.github.clans.fab.FloatingActionMenu
android:id="#+id/fabMenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
fab:menu_animationDelayPerItem="50"
fab:menu_backgroundColor="#B3FFFFFF"
fab:menu_buttonSpacing="0dp"
fab:menu_colorNormal="#DA4336"
fab:menu_colorPressed="#E75043"
fab:menu_colorRipple="#99FFFFFF"
fab:menu_fab_size="normal"
fab:menu_icon="#drawable/fab_add"
fab:menu_labels_colorNormal="#color/colorWhite"
fab:menu_labels_cornerRadius="3dp"
fab:menu_labels_ellipsize="none"
fab:menu_labels_margin="0dp"
fab:menu_labels_maxLines="-1"
fab:menu_labels_padding="8dp"
fab:menu_labels_paddingBottom="4dp"
fab:menu_labels_paddingLeft="8dp"
fab:menu_labels_paddingRight="8dp"
fab:menu_labels_paddingTop="4dp"
fab:menu_labels_position="left"
fab:menu_labels_showShadow="true"
fab:menu_labels_singleLine="false"
fab:menu_labels_textColor="#color/colorBlack"
fab:menu_labels_textSize="14sp"
fab:menu_openDirection="up"
fab:menu_shadowColor="#66000000"
fab:menu_shadowRadius="4dp"
fab:menu_shadowXOffset="1dp"
fab:menu_shadowYOffset="3dp"
fab:menu_showShadow="true"
>
<com.github.clans.fab.FloatingActionButton
android:id="#+id/menuIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_premium"
fab:fab_colorNormal="#color/colorPremium"
fab:fab_colorPressed="#color/colorPremiumDark"
fab:fab_colorRipple="#color/colorPremiumAccent"
fab:fab_label="Premium"
fab:fab_size="mini"
/>
<com.github.clans.fab.FloatingActionButton
android:id="#+id/menuOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_saves"
fab:fab_colorNormal="#color/colorSaves"
fab:fab_colorPressed="#color/colorSavesDark"
fab:fab_colorRipple="#color/colorSavesAccent"
fab:fab_label="Saves"
fab:fab_size="mini"/>
<com.github.clans.fab.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_edit"
fab:fab_colorNormal="#color/colorPrimary"
fab:fab_colorPressed="#color/colorPrimaryDark"
fab:fab_colorRipple="#color/colorAccent"
fab:fab_label="Write"
fab:fab_size="mini"/>
</com.github.clans.fab.FloatingActionMenu>
<TabHost android:id="#+id/tabHost"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<LinearLayout
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorWhite"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorWhite"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorWhite"
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="52dp"
android:layout_weight="0"
android:showDividers="none"/>
</LinearLayout>
</TabHost>
</android.support.design.widget.CoordinatorLayout>
So I'am wondering if my code will do some errors in the future use?
I mean, will it have out of memory problem since i am using only one viewpager for different adapters.
And for the tab with pagerTabStrip Am i doing it right implemeting it both?
Thanks.
So you are setting a new FragmentPagerAdapter on each TabHost, thus creating 3 new fragments at runtime when the user clicks another tab. This might cause confusion to the user and if the framgments load heavy resources, greater memory consumption and further user annoyance.