BottomAppBar 4 Icons not align properly - android

how can I align the icons properly as it?
This is my activity main xml with bottom app bar and floating action button.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragmentview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottom_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:backgroundTint="#color/bluPrincipale"
app:fabAlignmentMode="center"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_icona_menu_mappa"
app:layout_anchor="#id/bottom_app_bar" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
This is my activity main that make work for fragments I think.
MainActivity.java
package com.example.test.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.test.R;
import com.example.test.fragments.ConvenzioniFragment;
import com.example.test.fragments.DoveAndareFragment;
import com.example.test.fragments.HomeFragment;
import com.example.test.fragments.MappaFragment;
import com.example.test.fragments.MoreFragment;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton floatingActionButton;
private BottomAppBar bottomAppBar;
private boolean isFabTabbed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton = findViewById(R.id.fab);
bottomAppBar = findViewById(R.id.bottom_app_bar);
setSupportActionBar(bottomAppBar);
if(savedInstanceState == null) {
handleFrame(new HomeFragment());
}
handleFab();
}
private void handleFab() {
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isFabTabbed = !isFabTabbed;
if(isFabTabbed) {
handleFrame(new MappaFragment());
}
else
{
handleFrame(new HomeFragment());
}
}
});
}
private void handleFrame(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentTransaction.replace(R.id.fragmentview, fragment);
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bottomappbar_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()) {
case R.id.app_bar_home:
handleFrame(new HomeFragment());
return true;
case R.id.app_bar_dove_andare_sagre_eventi:
handleFrame(new DoveAndareFragment());
return true;
case R.id.app_bar_convenzioni:
handleFrame(new ConvenzioniFragment());
return true;
case R.id.app_bar_more:
handleFrame(new MoreFragment());
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my custom bottom app bar menu.
bottomappbar_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/app_bar_home"
android:icon="#drawable/ic_icona_menu_home"
android:title="Home"
app:showAsAction="always"
/>
<item
android:id="#+id/app_bar_dove_andare_sagre_eventi"
android:icon="#drawable/ic_icona_menu_dove_andare_sagre_eventi"
android:title="Dove Andare"
app:showAsAction="always"
/>
<item
android:id="#+id/app_bar_convenzioni"
android:icon="#drawable/ic_icona_menu_convenzioni"
android:title="Convenzioni"
app:showAsAction="always"
/>
<item
android:id="#+id/app_bar_more"
android:icon="#drawable/ic_icona_menu_more"
android:title="More"
app:showAsAction="always"
/>
</menu>
This is my gradle code. It's correct for me.
Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.test"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0-beta01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
But the bottom bar result not is as this:
picture correct
It's mine result :|
mineresult
I'm using latest material design.
Thanks for any helps!
Cris

Remove menu from BottomAppBar and add it in BottomNavigationView then add BottomNavigationView inside BottomAppBar, like this:
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragmentview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottom_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:fabAlignmentMode="center">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
style="#style/MyBottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemIconTint="#color/selector_bottom_navigation"
app:itemTextColor="#color/selector_bottom_navigation"
app:labelVisibilityMode="labeled"
app:menu="#menu/activity_home_bottom_nav" />
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic__right_arrow"
app:layout_anchor="#id/bottom_app_bar" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
If you do this, your items will appear in centre according to your expectation, but you may experience that icon of 2nd and 3rd item overlapped by FAB, to refrain from this situation, add an empty item in centre of your menu, like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/itemRenewals"
android:icon="#drawable/menu_renewals"
android:title="Renewals" />
<item
android:id="#+id/itemViewOwner"
android:icon="#drawable/menu_view_owner"
android:title="View User" />
<item
android:id="#+id/itemEmpty"
android:title=""/>
<item
android:id="#+id/itemEnquiry"
android:icon="#drawable/menu_enquiry"
android:title="Enquiry" />
<item
android:id="#+id/itemProfile"
android:icon="#drawable/menu_profile"
android:title="Profile" />
</menu>

Add this in your class,This code must solve your alignment problem
#SuppressLint("RestrictedApi")
private void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
item.setShiftingMode(false);
// set once again checked value, so view will be updated
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}

Related

Why does BottomNavigationView not get displayed?

I have followed the material guideline here but for some reason, the bottom navigation is not working for me. My app simply displays a white frame where the bottom navigation should be. What am I doing wrong? Please note that I commented out the onCreateOptionsMenu in my MainActivity.java shown below. If I uncomment this code, the items in my menu_bottom_navigation.xml show up in the app bar menu but I want to have them show up in the bottom navigation bar.
Build.gradle
...
implementation 'com.google.android.material:material:1.1.0'
...
Menu resource:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/discover"
android:enabled="true"
android:title="#string/title_activity_discover_movies"
android:icon="#drawable/ic_search_24px"/>
<item
android:id="#+id/favorites"
android:enabled="true"
android:title="#string/title_activity_favorite_movies"
android:icon="#drawable/ic_favorite_24px" />
</menu>
Layout resource:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".features.movieoptions.movielist.MainActivity">
<include
layout="#layout/toolbar_discover_movies"
android:id="#+id/toolbar_movie_list" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:background="#color/colorPrimary"
app:itemBackground="#color/colorPrimary"
app:itemTextColor="#color/colorTextIcons"
app:menu="#menu/menu_bottom_navigation"/>
</FrameLayout>
</LinearLayout>
MainActivity.java
package edu.bu.metcs.activitylifecycle.features.movieoptions.movielist;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import edu.bu.metcs.activitylifecycle.R;
import edu.bu.metcs.activitylifecycle.features.movieoptions.movielist.discover.DiscoverFragment;
import edu.bu.metcs.activitylifecycle.features.movieoptions.movielist.favorites.FavoritesFragment;
import edu.bu.metcs.activitylifecycle.shared.FragmentUtility;
/**********************************************************************************************************************
* This activity manages the apps fragments and decides which fragment should be displayed to the user.
*
* #author mlewis
* #version June 5, 2020
*********************************************************************************************************************/
public class MainActivity extends AppCompatActivity {
// Invariant of the MovieListActivity.java class
// 1. A shareActionProvider sends an implicit intent to apps capable of handling the text/plain MIME type.
// 2. The TAG is used by the Logcat for informational purposes.
private DiscoverFragment discoverFragment;
private FavoritesFragment favoritesFragment;
private static final String TAG = MainActivity.class.getSimpleName();
/**
* protected void onCreate(Bundle savedInstanceState)
* Performs initial Activity set up.
*
* #param savedInstanceState A bundle for any saved state from prior sessions that were destroyed.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
discoverFragment = DiscoverFragment.newInstance();
favoritesFragment = FavoritesFragment.newInstance();
// Show discover fragment by default
setUpFragment(discoverFragment);
}
setUpBottomNavigation();
setUpToolbar();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.menu_bottom_navigation, menu);
// return true;
// }
private void setUpFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentUtility.fragmentTransaction(fragmentManager, R.id.fragment_container, fragment);
}
private void setUpBottomNavigation() {
Log.d(TAG, "Setting bottom nav.");
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.discover:
Log.d(TAG, "discover was clicked.");
setUpFragment(discoverFragment);
return true;
case R.id.favorites:
Log.d(TAG, "favorites was clicked.");
setUpFragment(favoritesFragment);
return true;
}
return false;
}
});
}
private void setUpToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar_movie_list);
setSupportActionBar(toolbar);
}
}
Please see the white section at the bottom of the screen to see the issue:
As i Checked your layout. i found the mistake
1. Fragment Container(Frame layout) having wrong margin bottom
2. Need to add wight for fragment container(Frame Layout)
Corrected code as below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".features.movieoptions.movielist.MainActivity">
<include
layout="#layout/toolbar_discover_movies"
android:id="#+id/toolbar_movie_list" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
app:itemBackground="#color/colorPrimary"
app:itemTextColor="#color/colorTextIcons"
app:menu="#menu/menu_bottom_navigation"/>
</FrameLayout>
</FrameLayout>
</LinearLayout>

i have a problem with data binding in android studio

I suddenly found that my binding. <widget name> is not working.
Then I noticed that emulator dropdown selection isn't working as well.
I am attaching the screenshots of my IDE for reference.
Gradle dependencies:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.jakewharton:butterknife:10.2.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.annotation:annotation:1.1.0'
implementation "androidx.appcompat:appcompat:1.1.0"
implementation "androidx.appcompat:appcompat-resources:1.1.0"
implementation "androidx.autofill:autofill:1.0.0"
implementation "androidx.core:core:1.1.0"
implementation 'com.google.android.material:material:1.0.0'
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.0'
implementation 'com.google.firebase:firebase-auth:19.2.0'
}
main activity code
package com.example.myapplication.ui.activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.example.myapplication.R;
import com.example.myapplication.databinding.ActivityMainBinding;
import com.example.myapplication.pojo.IncomeModel;
import com.example.myapplication.pojo.PaymentModel;
import com.example.myapplication.ui.adapter.IncomeListAdapter;
import com.example.myapplication.ui.adapter.PaymentsListAdapter;
import com.example.myapplication.ui.viewModel.IncomeViewModel;
import com.example.myapplication.ui.viewModel.PaymentViewModel;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static float totalPayment;
private static float totalIncome;
private static boolean paymentView = true;
PaymentViewModel paymentViewModel;
IncomeViewModel incomeViewModel;
ViewDataBinding binding;
PaymentsListAdapter adapterP;
IncomeListAdapter adapterI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setDataBindingAndObservers();
setMenuItem();
paymentRecyclerView();
incomeRecyclerView();
setPaymentRecycler();
setTotalSettle();
setFabClick();
}
private void setDataBindingAndObservers() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
paymentViewModel = new ViewModelProvider(this).get(PaymentViewModel.class);
incomeViewModel = new ViewModelProvider(this).get(IncomeViewModel.class);
paymentViewModel.paymentLiveList.observe(this,paymentModels -> onPaymentLiveListChange(paymentModels));
incomeViewModel.incomLiveList.observe(this, incomeModels -> onIncomeLiveListChange(incomeModels));
paymentViewModel.totalPayment.observe(this,aFloat -> onTotalPaymentChange(aFloat));
incomeViewModel.totalIncome.observe(this, aFloat -> onTotalIncomeChange(aFloat));
}
private void setMenuItem() {
setSupportActionBar(binding.toolbar);
binding.toolbar.inflateMenu(R.menu.item_menu);
binding.toolbar.setOnMenuItemClickListener(item -> {
switch (item.getItemId()) {
case R.id.item_switch :
switchItemClicked();
return true;
default:
return false;
}
});
}
private void paymentRecyclerView() {
adapterP = new PaymentsListAdapter();
binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void incomeRecyclerView() {
adapterI = new IncomeListAdapter();
binding.recyclerView.setAdapter(adapterI);
binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
private void switchItemClicked() {
if(paymentView) setIncomeRecycler();
else setPaymentRecycler();
invalidateOptionsMenu();
}
private void setPaymentRecycler() {
binding.recyclerView.setAdapter(adapterP);
paymentView = true;
}
private void setIncomeRecycler() {
binding.recyclerView.setAdapter(adapterI);
paymentView = false;
}
private void setTotalSettle() {
binding.tvTotalSettle.setText(String.format("%s", totalIncome - totalPayment));
}
private void setFabClick() {
binding.floatingActionButton.setOnClickListener(v -> {
if(paymentView)paymentViewModel.getPaymentList();
else incomeViewModel.getIncomeList();
});
}
private void onPaymentLiveListChange(ArrayList<PaymentModel> paymentModels) {
adapterP.setPaymentList(paymentModels);
}
private void onIncomeLiveListChange(ArrayList<IncomeModel> incomeModels) {
adapterI.setIncomeList(incomeModels);
}
private void onTotalPaymentChange(float aFloat) {
totalPayment = aFloat;
setTotalSettle();
}
private void onTotalIncomeChange(float aFloat) {
totalIncome = aFloat;
setTotalSettle();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.item_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.item_switch) switchItemClicked();
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.item_switch);
if (paymentView) {
item.setTitle(R.string.item_income);
} else {
item.setTitle(R.string.item_payments);
}
return super.onPrepareOptionsMenu(menu);
}
}
activity_main layout
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
</data>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="12dp"
android:clickable="true"
android:focusable="true"
app:srcCompat="#android:drawable/ic_menu_add" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
android:paddingBottom="8dp"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
app:layout_constraintBottom_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:foregroundTint="#2B2B2B">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
app:layout_scrollInterpolator="#android:anim/decelerate_interpolator"
app:toolbarId="#+id/toolbar">
<androidx.cardview.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|start"
android:layout_margin="4dp">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="hi!">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_total_settle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="#string/tv_total_payment"
android:textSize="#dimen/font_dim_big"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/tv_total"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tv_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="#string/tv_total"
android:textSize="#dimen/font_dim_big"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
</androidx.cardview.widget.CardView>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
edit :
1 - i have tried removing layout and data tags ,
and re-adding them
2- i have tried rebuilding the project
solved :)
this line seemed to be edited by the ide to be like this
ViewDataBinding binding;
but it should be like this
ActivityMainBinding binding;

Tab titles not display using TabLayout

I am following Android tutorials by Google at Udacity. I tried to make a simple viewpager app with tabs, but tabs' names are not displayed. What's curious is that I did exactly the same coding with the tutorial, and these add code alone creates tabs on tutorial app just fine. Please help me. Thanks!
MainActivity:
package com.example.mari.viewpagerpracsec;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
CustomPagerAdapter adapter = new CustomPagerAdapter(this, getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
Viewpager Adapter:
package com.example.mari.viewpagerpracsec;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
public class CustomPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public int getCount() {return 3;}
#Override
public Fragment getItem(int position) {
if (position==0) {
return new FirstFragment();
}else if (position==1) {
return new SecondFragment();
}else if (position==2){
return new ThirdFragment();
}else {
return new FirstFragment();
}
}
#Override
public CharSequence getPageTitle(int position) {
if (position==0) {
return mContext.getString(R.string.first);
} else if (position==1) {
return mContext.getString(R.string.second);
} else {
return mContext.getString(R.string.third);
}
}
}
Fragment 1
package com.example.mari.viewpagerpracsec;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
Fragment2
package com.example.mari.viewpagerpracsec;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SecondFragment extends Fragment {
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false);
}
}
Fragment 3
package com.example.mari.viewpagerpracsec;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ThirdFragment extends Fragment {
public ThirdFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_third, container, false);
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
style="#style/ImageTab"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
fragment 1
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mari.viewpagerpracsec.FirstFragment">
<ImageView
android:id="#+id/image_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/first_image"
android:scaleType="centerCrop"/>
</FrameLayout>
fragment 2
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mari.viewpagerpracsec.SecondFragment">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/second_image"
android:scaleType="fitCenter"/>
</FrameLayout>
fragment 3
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mari.viewpagerpracsec.ThirdFragment">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/third_image"
android:scaleType="centerCrop"/>
</FrameLayout>
colors
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>
strings
<resources>
<string name="app_name">View Pager Prac sec</string>
<string name="first">first</string>
<string name="second">second</string>
<string name="third">third</string>
</resources>
styles
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="actionBarStyle">#style/MiwokAppBarStyle</item>
<item name="android:windowContentOverlay">#null</item>
</style>
<!-- App bar style -->
<style name="MiwokAppBarStyle" parent="style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<!-- Remove the shadow below the app bar -->
<item name="elevation">0dp</item>
</style>
<!-- Style for a tab that displays a category name -->
<style name="ImageTab" parent="Widget.Design.TabLayout">
<item name="tabIndicatorColor">#android:color/white</item>
<item name="tabSelectedTextColor">#android:color/white</item>
<item name="tabTextAppearance">#style/ImageTabTextAppearance</item>
<item name="tabBackground">#color/colorPrimary</item>
</style>
<!-- Text appearance style for a category tab -->
<style name="ImageTabTextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textColor">#A8A19E</item>
</style>
</resources>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.mari.viewpagerpracsec"
minSdkVersion 22
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:design:25.3.1'
testCompile 'junit:junit:4.12'
}
In activity_main, your ViewPager have layout_height:match_parent. It's make your TabLayout doesn't have space on screen.
Your ViewPager should be like:
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
or You can just move the TabLayout to above of ViewPager
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
style="#style/ImageTab"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Try with this layout insted of your activity_main layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Your viewpager's height is taking the whole screen space. Try to make it smaller not match_parent. Even you could add margin bottom like this.
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_marginBottom="60dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />

CollapsingToolbarLayout doesn't work: The following classes could not be instantiated and java.lang.NoSuchMethodError

The CollapsingToolbarLayout crash everytime my application when I try to open it on the device, idk why this problem.
This is the problem:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.projectz.teamrocket.thebusapp/com.android.projectz.teamrocket.thebusapp.activity.DetailViewerActivity}: android.view.InflateException: Binary XML file line #16: Binary XML file line #16: Error inflating class android.support.design.widget.CollapsingToolbarLayout
And this is the other error which is throw inside android studio (preview of app design)
java.lang.NoSuchMethodError: android.support.v4.graphics.drawable.DrawableCompat.setLayoutDirection(Landroid/graphics/drawable/Drawable;I)V
the xml file:
<?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"
tools:context="com.android.projectz.teamrocket.thebusapp.activity.DetailViewerActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarDetailViewer"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager 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/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.android.projectz.sciacallo.thebusapp.com.android.projectz.teamrocket.thebusapp.activity.DetailViewerActivity"
tools:showIn="#layout/activity_detail_viewer">
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#color/colorPrimaryDark"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff"
app:layout_behavior="" />
</android.support.v4.view.ViewPager>
<View
android:id="#+id/shadowView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F2FFFFFF"
android:visibility="invisible" />
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/fab_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
fab:fab_addButtonColorNormal="#color/colorPrimaryDark"
fab:fab_addButtonColorPressed="#color/colorPrimary"
fab:fab_addButtonPlusIconColor="#color/white"
fab:fab_labelStyle="#style/menu_labels_style">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_favorit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_icon="#drawable/ic_star_off"
fab:fab_colorNormal="#color/colorFAB2"
fab:fab_colorPressed="#color/colorFAB2pressed"
fab:fab_size="mini"
fab:fab_title="#string/fab_favorit" />
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
fab:fab_icon="#drawable/ic_share"
fab:fab_colorNormal="#color/colorFAB1"
fab:fab_colorPressed="#color/colorFAB1pressed"
fab:fab_size="mini"
fab:fab_title="#string/fab_share" />
</com.getbase.floatingactionbutton.FloatingActionsMenu>
<!--
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_favorit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="160dp"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/ic_star_off"
android:visibility="invisible"
app:backgroundTint="#color/colorFAB2"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="90dp"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/ic_message"
android:visibility="invisible"
app:backgroundTint="#color/colorFAB1"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_more"
app:backgroundTint="#color/colorPrimaryDark"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
-->
The build.grandle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '24.0.0'
defaultConfig {
applicationId "com.android.projectz.teamrocket.thebusapp"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "0.6"
vectorDrawables.useSupportLibrary = true
}
...
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile files('libs/commons-net-3.5.jar')
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'com.android.support:support-v4:23.3.0'
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
compile 'com.github.paolorotolo:appintro:4.1.0'
compile 'com.afollestad.material-dialogs:commons:0.9.1.0'
compile 'jp.wasabeef:recyclerview-animators:1.3.0'
compile 'com.getbase:floatingactionbutton:1.10.1'
testCompile 'junit:junit:4.12'
}
and to finish this is the style.xml file:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="AppTheme.ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark" />
<style name="AppTheme.Toolbar" parent="Theme.AppCompat.Light">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="InputTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/yellow</item>
</style>
<style name="menu_labels_style">
<item name="android:background">#drawable/fab_label_background</item>
<item name="android:textColor">#color/white</item>
</style>
and this is the jva file:
package com.android.projectz.teamrocket.thebusapp.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Toast;
import com.android.projectz.teamrocket.thebusapp.R;
import com.android.projectz.teamrocket.thebusapp.util.ShareUtil;
public class DetailViewerActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = DetailViewerActivity.class.getSimpleName();
boolean fabStatus = false;
SectionsPagerAdapter sectionsPagerAdapter;
ViewPager viewPager;
private boolean isFavorit = false;
private String busID;
private ShareUtil share;
private Boolean isFabOpen = false;
private Animation fab_open, fab_close, rotate_forward, rotate_backward;
Animation show_fab_1, hide_fab_1;
private com.getbase.floatingactionbutton.FloatingActionButton fabNormal;
private com.getbase.floatingactionbutton.FloatingActionButton fabShare;
private com.getbase.floatingactionbutton.FloatingActionButton fabFavorit;
private View mShadowView;
public Animation fadeIn, fadeOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_viewer);
DetailViewerActivity.this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_left);
Toolbar toolbarDetail = (Toolbar) findViewById(R.id.toolbarDetailViewer);
setSupportActionBar(toolbarDetail);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_in);
fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_out);
share = new ShareUtil();
//fabNormal = (com.getbase.floatingactionbutton.FloatingActionButton) findViewById(R.id.fab_normal);
fabShare = (com.getbase.floatingactionbutton.FloatingActionButton) findViewById(R.id.fab_share);
fabFavorit = (com.getbase.floatingactionbutton.FloatingActionButton) findViewById(R.id.fab_favorit);
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_backward);
mShadowView = findViewById(R.id.shadowView);
//fabNormal.setOnClickListener(this);
fabShare.setOnClickListener(this);
fabFavorit.setOnClickListener(this);
if (isFavorit) {
fabFavorit.setSize(com.getbase.floatingactionbutton.FloatingActionButton.SIZE_MINI);
fabFavorit.setIcon(R.drawable.ic_star_on);
fabFavorit.setStrokeVisible(false);
fabFavorit.refreshDrawableState();
} else {
fabFavorit.setSize(com.getbase.floatingactionbutton.FloatingActionButton.SIZE_MINI);
fabFavorit.setIcon(R.drawable.ic_star_off);
fabFavorit.setStrokeVisible(false);
fabFavorit.refreshDrawableState();
}
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(sectionsPagerAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// write your code here
this.finish();
DetailViewerActivity.this.overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
}
return true;
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.fab_share: // fab per lo sharing della tratta:
/**
* testo:
* Stò guardando questa tratta: <nome-tratta>
* anche te puoi farlo, scarica gratuitamente l'app...
*/
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, TAG + ": test_share_fab_share_button_tragitto");
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_title)));
break;
case R.id.fab_favorit: // fab per il set favorit della tratta
/**
* qui bisogna fare i controlli con il database interno per verificare la
* veridicità dei dati: se la tratta è tra i favorit dell'utente
*/
if (isFavorit == true) {
isFavorit = false;
fabFavorit.setIcon(R.drawable.ic_star_on);
Snackbar snackbar = Snackbar
.make(v, "Percorso salvato nei preferiti", Snackbar.LENGTH_LONG)
.setAction("INDIETRO", new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar snackbar1 = Snackbar.make(view, "Percorso eliminato", Snackbar.LENGTH_SHORT);
snackbar1.show();
fabStatus = false;
fabFavorit.setImageResource(R.drawable.ic_star_off);
fabFavorit.refreshDrawableState();
}
});
snackbar.show();
//Toast.makeText(DetailViewerActivity.this, String.valueOf(isFavorit), Toast.LENGTH_SHORT).show();
} else {
isFavorit = true;
fabFavorit.setIcon(R.drawable.ic_star_off);
//Toast.makeText(DetailViewerActivity.this, String.valueOf(isFavorit), Toast.LENGTH_SHORT).show();
}
fabFavorit.refreshDrawableState();
break;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
this.finish();
DetailViewerActivity.this.overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
View view = null;
switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1: /* visualizzazione dei dettaglio del viaggio */
view = getTravelView(inflater);
break;
case 2: /* visualizzazione dei servizi disponibili (città) */
view = getServiceView(inflater);
break;
case 3: /* visualizzazione delle pubblicità dei qualiasi cosa (supermercati, scarpe, viagra ...) */
view = getAdvertisingView(inflater);
break;
}
return view; //ritornare un layout
}
public View getTravelView(LayoutInflater inflater) {
return inflater.inflate(R.layout.travel_layout, null);
}
public View getServiceView(LayoutInflater inflater) {
return inflater.inflate(R.layout.service_layout, null);
}
public View getAdvertisingView(LayoutInflater inflater) {
return inflater.inflate(R.layout.advertising_layout, null);
}
}
public boolean isBusFavorit() {
return isFavorit;
}
public void setFavorit(boolean fav) {
isFavorit = fav;
}
}
Ok I solved the problem by changing the version of SDK, I change sdk library version from 23.4.0 to 24.0.0, and it works.
I follow this post https://stackoverflow.com/a/39119028/5996106 #KarandeepAtwal
Note that as the Design library depends on the Support v4 and AppCompat Support Libraries, those will be included automatically when you add the Design library dependency. So you should Use only same versions.Its problem of conflicting -
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
compile 'com.android.support:design:23.3.0' //23.4.0
//try to delete these below libraries and see if it works
compile 'com.android.support:appcompat-v7:23.3.0' //23.4.0
compile 'com.android.support:support-v4:23.3.0' //23.4.0
compile ('com.android.support:support-v4:23.4.0'){
force = true;
}
Use this in your gradle file.
Update manifest like this
compile 'com.android.support:support-v4:23.3.0'
{
force = true;
}

Android Toolbar return button didn't work after adding productFlavors

Before adding productFlavors in build.gradle(Module:app), the return button in Toolbar works.
But once I added productFlavors into build.gradle(Module:app) for Build >> Generate Signed APK..., the return button become invalid.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.comp548.note">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NoteEditActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
</application>
</manifest>
build.gradle(Module:app) after adding productFlavors:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "com.comp548.note"
minSdkVersion 19
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
free {
applicationId "com.comp548.note.free"
versionName "1.0-free"
}
paid {
applicationId "com.comp548.note.paid"
versionName "1.0-paid"
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.2.0'
}
toolbar.xml in layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
app:theme="#style/ThemeOverlay.AppCompat.Dark"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
tools:ignore="Overdraw">
</android.support.v7.widget.Toolbar>
activity_note_edit.xml in layout:
<?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"
tools:context="com.comp548.note.NoteEditActivity">
<include layout="#layout/toolbar"
android:id="#+id/note_edit_toolbar" />
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fragment_margin"
android:name="com.comp548.note.NoteEditFragment"
android:id="#+id/fNoteEdit"
android:layout_centerHorizontal="true"
tools:layout="#layout/fragment_note_edit"
android:layout_below="#id/note_edit_toolbar"/>
</RelativeLayout>
MainActivity.java:
package com.comp548.note;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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);
Toolbar toolbar = (Toolbar)findViewById(R.id.note_list_toolbar);
// Set the Toolbar to act as the ActionBar for this Activity window
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setTitle(R.string.toolbar_title);
}
getSupportActionBar().setIcon(R.drawable.ic_toolbar);
FloatingActionButton fabAdd = (FloatingActionButton)findViewById(R.id.fabAdd);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, NoteEditActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
NoteEditActivity.java:
package com.comp548.note;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class NoteEditActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_edit);
Toolbar toolbar = (Toolbar)findViewById(R.id.note_edit_toolbar);
// Set the Toolbar to act as the ActionBar for this Activity window
setSupportActionBar(toolbar);
// Enable return button
if(getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
NoteEntity noteEntity = (NoteEntity) intent.getSerializableExtra("noteEntity");
// Set values for Views in NoteEditFragment
if (noteEntity != null) {
NoteEditFragment noteEditFragment = (NoteEditFragment)getSupportFragmentManager().findFragmentById(R.id.fNoteEdit);
noteEditFragment.setValues(noteEntity);
}
}
}
App screenshots:
After remove the productFlavors from build.gradle(Module:app) the return button works again.
Why the return button on Toolbar didn't work after adding productFlavors.
How to fix it if I still want to add productFlavors?
Okay in your NoteEditActivity add the callback method onOptionsItemSelected(MenuItem item) and do the following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
It should fix your issue, allowing the toolbar back button to execute the action of the back button. Hope this helps.
Reason: You put different applicationId for each flavor.
In manifest you set metadata for parent activity, but during building flavor all packages are automatically moved to package com.comp548.note.free or com.comp548.note.paid. Your metadata points to com.comp548.note.MainActivity though your actual activity is located under com.comp548.note.paid|free.MainActivity.
Solutions:
Create separate manifests for each flavor with metadata points to correct packages.
Handle it at runtime like KudzieChase described.

Categories

Resources