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;
Related
Basically I have a app with two Screen. ScreenOne and ScreenTwo. In the first Screen, i mean in MainActivity viewBinding is working fine. But on a perticular button click it will redirect to the second screen. Now there is the problem.
the error massage is -
error: cannot find symbol import com.example.demoapp.databinding.DragAndDropBinding;
But in the first Screen It's working fine.
MainActivity[FirstScreen]
//Working Fine
package com.example.demoapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.demoapp.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.dragOnly.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DragActivity.class);
v.getContext().startActivity(intent);
}
});
}
}
ActivityMain.xml file
<?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">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:layout_centerVertical="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dragAndDrop"
android:text="Drag and Drop"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag"
android:id="#+id/dragOnly"/>
</LinearLayout>
</RelativeLayout>
and the DragAndDropActivity[Second Screen]
//Showing error for import com.example.demoapp.databinding.DragAndDropBinding;
package com.example.demoapp;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.demoapp.databinding.ActivityMainBinding;
import com.example.demoapp.databinding.DragAndDropBinding; //Error
public class DragActivity extends AppCompatActivity {
TextView textView;
DragAndDropBinding binding;
float xPosition, yPosition, xPrevious, yPrevious;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag_and_drop);
textView = findViewById(R.id.dragButton);
textView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int point = event.getActionMasked();
switch (point) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
xPrevious = event.getX();
yPrevious = event.getY();
return true;
case MotionEvent.ACTION_MOVE:
float dx = event.getX() - xPrevious;
float dy = event.getY() - yPrevious;
xPosition += dx;
yPosition += dy;
v.setX(xPosition - v.getWidth());
v.setY(yPosition - v.getHeight());
return true;
default:
return false;
}
}
});
}
}
DragAndDrop.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag Me any Where"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/dragButton"
android:background="#056"
android:padding="8dp"
android:textColor="#FFF"/>
</RelativeLayout>
build.gradle[App]
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.demoapp"
minSdkVersion 23
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'
}
}
viewBinding {
enabled = true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
Android Studio version 3.6.1 and gradle plugin classpath 'com.android.tools.build:gradle:3.6.1'
I can see that you are actually not using ViewBinding in the second activity. You are just importing it generated class. Proguard obfuscates unused classes at runtime and it is thinking that you are not using your generated view binding class (which is right, you are just importing it.) so use it as you used in the first activity. It will work.
So, I'm trying to create an onclick listener on a button using databinding using this tutorial.
databinding tutorial so as far as when I keep the onclick inside my activity_main.xml layout the button click works. But I want to send my data to an include_main_layout.xml but it tells me I have the error..
build.gradle(app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
dataBinding {
enabled = true
}
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.datahelpsworld"
minSdkVersion 23
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.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
user = new User();
user.setEmail("Ebola chebola chernobyl caronvirus");
user.setName("dilo dilo bolo bolo");
binding.setUser(user);
MyClickHandlers handlers = new MyClickHandlers(this);
binding.setHandlers(handlers);
}
public class MyClickHandlers {
Context context;
public MyClickHandlers(Context context) {
this.context = context;
}
public void onFabClicked(View view) {
user.setName("Ashutosh is awesome");
user.setEmail("email address is magical and cannot be retrieved");
Toast.makeText(getApplicationContext(), "FAB clicked!", Toast.LENGTH_SHORT).show();
}
public void onButtonClick() {
Toast.makeText(getApplicationContext(), "Button clicked!", Toast.LENGTH_SHORT).show();
}
public void onButtonClickWithParam(View view, User user) {
Toast.makeText(getApplicationContext(), "Button clicked! Name: " + user.getName(), Toast.LENGTH_SHORT).show();
}
public boolean onButtonLongPressed(View view) {
Toast.makeText(getApplicationContext(), "Button long pressed!", Toast.LENGTH_SHORT).show();
return false;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="handlers"
type="com.example.datahelpsworld.MainActivity.MyClickHandlers" />
<variable
name="user"
type="com.example.datahelpsworld.User" />
</data>
<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="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">
<include
layout="#layout/main_layout"
bind:handlers="#{handlers}"
bind:user="#{user}" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:longClickable="true"
android:onClick="#{(v)->handlers.onFabClicked()}"
android:text="activity main layout">
</Button>
</LinearLayout>
</layout>
main_layout.xml
<layout>
<data>
<variable
name="user"
type="com.example.datahelpsworld.User" />
<variable
name="handlers"
type="com.example.datahelpsworld.MainActivity.MyClickHandlers" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{user.name}">
</TextView>
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#{user.email}">
</TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#={(v)->handlers.onButtonClick()}"
android:text="inside include">
</Button>
</LinearLayout>
</layout>
my error is the following lines..
error: cannot find symbol class ActivityMainBindingImpl
I tried cleaning the project and rebuilding from the ground base but still no luck. What is it that I'm doing wrong?
Problem is here.
android:onClick="#{(v)->handlers.onFabClicked()}"
it should be android:onClick="#{handlers.onFabClicked()}" simple.
If you want to pass view parameter from xml then your onClick methos should be like below.
android:onClick="#{(v)->handlers.onFabClicked(v)}"
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);
}
}
I have to add sign in with google feature to my app. I have tried several tutorials but nothing works. Whenever I select an account from the list, that pop up gets closed and nothing happens. I don't know what is the problem since there is no errors showing on the logcat.
Login.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
public class Login extends AppCompatActivity {
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth auth;
RelativeLayout googlesignin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this,gso);
googlesignin = (RelativeLayout) findViewById(R.id.googlesignin);
googlesignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, 101);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = auth.getCurrentUser();
Intent i = new Intent(getApplicationContext(),Homewindow.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(),"User Logged In Successfully",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),"Login Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
}
activity_login
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00BFFF"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<RelativeLayout
android:id="#+id/loginmain"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/logincontents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/relativelayout_custom"
android:orientation="vertical"
android:padding="20dp">
<RelativeLayout
android:id="#+id/googlesignin"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="40dp"
android:orientation="horizontal"
android:background="#drawable/loginlayout">
<ImageView
android:id="#+id/googleicon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/googleicon"/>
<TextView
android:id="#+id/googletext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/googleicon"
android:fontFamily="#font/averia_gruesa_libre"
android:text="Sign in with Google"
android:textColor="#db3236"
android:textSize="14dp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/facebooksignin"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_below="#id/googlesignin"
android:layout_marginTop="40dp"
android:background="#drawable/loginlayout">
<ImageView
android:id="#+id/facebookicon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/facebookicon"/>
<TextView
android:id="#+id/facebooktext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:fontFamily="#font/averia_gruesa_libre"
android:layout_toRightOf="#id/facebookicon"
android:text="Sign in with Facebook"
android:textColor="#3b5998"
android:textSize="14dp"
android:textStyle="bold" />
</RelativeLayout>
<TextView
android:id="#+id/skipbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/facebooksignin"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:fontFamily="#font/averia_gruesa_libre"
android:paddingTop="5dp"
android:text="SKIP NOW >>"
android:textColor="#00BFFF"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/profileicon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:layout_above="#id/logincontents">
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerHorizontal="true"
android:src="#drawable/profile_icon"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
Here I used onClickListener for the Relative layout containing googleicon and text.
build.gradle (app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.1"
defaultConfig {
vectorDrawables.useSupportLibrary = true
applicationId "com.example.parethumukal"
minSdkVersion 18
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.firebase:firebase-auth:18.1.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//noinspection GradleCompatible
implementation "com.google.android.material:material:1.0.0-rc01"
implementation 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
//noinspection GradleCompatible
def lifecycle_version = "2.0.0"
// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation files('libs\\YouTubeAndroidPlayerApi.jar')
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-database:18.0.0'
implementation 'com.google.firebase:firebase-storage:18.1.0'
implementation 'de.hdodenhof:circleimageview:3.0.0'
}
apply plugin: 'com.google.gms.google-services'
build.gradle(project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath 'com.google.gms:google-services:4.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven {
url "https://maven.google.com"
}
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
logcat error
07-23 21:48:22.994 21934-21934/com.example.parethumukal E/MultiWindowProxy: getServiceInstance failed!
07-23 21:48:27.924 21934-21982/com.example.parethumukal E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb37a4d60
I don't know if any errors with my codes. Codes are taken from firebase site.
Try this
GoogleSignInOptions gso;
GoogleApiClient googleApiClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.firebase_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.enableAutoManage(this, null)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
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;
}