Chrobin
Chrobin

Reputation: 63

Toolbar doesn't set elevation on create or in XML

I'm currently creating an Android app for school but still want to give my best. I'm pretty new to Android development and coding in general. The app is supposed to be a stock market game. (Btw, I'm German, so there might be some German variables) The app should have a similar style to Google's recent one with the Pixel 2 and Android Pie. Thus, the toolbar should have no drop shadow when created but it should appear when scrolling, like in the Pixel 2's settings app (e.g. the battery tab). The drop shadow appears when scrolling and disappears when arriving at the top, but the toolbar starts with a drop shadow although I have set the android:elevation to 0 in the XML and also toolbar.setElevation(0) in the onCreate method. Why does this happen? This method works in the OnScrollChangedListener!

The Java code:

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<JSONObject> jObjList = new ArrayList<>();
    private FloatingActionButton fab;
    private TextView moneyTxt;
    private TextView sharesTxt;
    private TextView sumTxt;
    private Toolbar toolbar;
    private AppBarLayout toolbarLayout;
    private RecyclerView recyclerShares;
    private SharesAdapter sAdapter;
    private NestedScrollView scrollMain;
    private SwipeRefreshLayout refreshMain;
    private float money;
    private float sharesWorth;
    private boolean isRefreshing;
    private JSONObject jObj = new JSONObject();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = findViewById(R.id.abMain);
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);

        fab = findViewById(R.id.fabMain);
        moneyTxt = findViewById(R.id.moneyTxt);
        sharesTxt = findViewById(R.id.sharesTxt);
        sumTxt = findViewById(R.id.sumTxt);
        toolbarLayout = findViewById(R.id.abMainLayout);
        recyclerShares = findViewById(R.id.recyclerShares);
        scrollMain = findViewById(R.id.scrollMain);
        scrollMain.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        refreshMain = findViewById(R.id.refreshMain);
        isRefreshing = false;

        try {
            jObj.put("name", "BMW");
            jObj.put("worth", 143.23);
            jObj.put("count", 5);
            jObj.put("change", -1.5);

            jObjList.add(jObj);
        } catch (JSONException e) {
        }

        sAdapter = new SharesAdapter(jObjList);
        RecyclerView.LayoutManager cLayoutManager = new CustomGridLayoutManager(getApplicationContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        recyclerShares.setLayoutManager(cLayoutManager);
        recyclerShares.setItemAnimator(new DefaultItemAnimator());
        recyclerShares.setAdapter(sAdapter);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SharesActivity.class);
                startActivity(intent);
            }
        });

        toolbarLayout.setElevation(0); //TODO: Stackoverflow nach Lösung fragen
        scrollMain.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                int scroll = scrollMain.getScrollY();
                if (scroll == 0) {
                    toolbarLayout.setElevation(0);
                } else {
                    toolbarLayout.setElevation(8);
                }
            }
        });

        refreshMain.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh(MainActivity.this);
            }
        });

        refresh(MainActivity.this);
    }

    private void refresh(Context context) {
        isRefreshing = true;

        SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        SharedPreferences.Editor sharedPrefEdit = sharedPref.edit();

        if (sharedPref.getBoolean("isFirstRun", true)) {
            sharedPrefEdit.putBoolean("isFirstRun", false);
            sharedPrefEdit.putFloat(getString(R.string.moneyShared), 5000);
            sharedPrefEdit.apply();
        }

        float shareWorth = 0;

        for (int i = 0; i < jObjList.size(); i++) {
            try {
                shareWorth += jObjList.get(i).getDouble("worth") * jObjList.get(i).getDouble("count");
            } catch (JSONException e) {
            }
        }
        sharedPrefEdit.putFloat(getString(R.string.sharesWorthShared), shareWorth);
        sharedPrefEdit.commit();

        money = sharedPref.getFloat(getString(R.string.moneyShared), 0);
        sharesWorth = sharedPref.getFloat(getString(R.string.sharesWorthShared), 0);

        moneyTxt.setText(String.format("%.2f€", money));
        sharesTxt.setText(String.format("%.2f€", sharesWorth));
        sumTxt.setText(String.format("%.2f€", money + sharesWorth));

        if(isRefreshing) {
            isRefreshing = false;
            refreshMain.setRefreshing(isRefreshing);
        }

        Toast.makeText(MainActivity.this, "Alles neugeladen", Toast.LENGTH_SHORT).show();
    }

    public void onShareClick(View v) {
        Intent i = new Intent(MainActivity.this, CompanyActivity.class);
        try {
            i.putExtra("name", jObj.getString("name"));
            i.putExtra("worth", jObj.getDouble("worth"));
        } catch (JSONException e) {
            i.putExtra("name", "Fehler");
            i.putExtra("worth", 0);
        }
        startActivity(i);
    }
}

The XML code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/abMainLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="0dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/abMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorBackgroundAccent"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    </android.support.design.widget.AppBarLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:backgroundTint="@color/colorBackground"
        android:src="@drawable/ic_note_add"
        app:borderWidth="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refreshMain"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/abMainLayout">

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/scrollMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusableInTouchMode="true"
            app:layout_constraintTop_toBottomOf="@+id/abMainLayout">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <GridLayout
                    android:id="@+id/gridMoney"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/colorBackgroundAccent"
                    android:orientation="horizontal"
                    android:paddingBottom="@dimen/activity_vertical_margin"
                    android:paddingTop="24dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@id/abMain">

                    <TextView
                        android:id="@+id/sumTxt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_columnSpan="5"
                        android:layout_columnWeight="1"
                        android:layout_gravity="center"
                        android:layout_marginBottom="16dp"
                        android:layout_marginTop="8dp"
                        android:layout_row="1"
                        android:textColor="@color/colorDarkText"
                        android:textSize="50sp"
                        android:textStyle="bold" />

                    <ImageView
                        android:id="@+id/moneyImg"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_column="1"
                        android:layout_columnWeight="1"
                        android:layout_gravity="right|center_vertical"
                        android:layout_row="2"
                        android:background="@android:color/transparent"
                        android:scaleX="0.5"
                        android:scaleY="0.5"
                        app:srcCompat="@drawable/ic_money" />

                    <TextView
                        android:id="@+id/moneyTxt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_column="2"
                        android:layout_columnWeight="1"
                        android:layout_gravity="left|center_vertical"
                        android:layout_row="2"
                        android:background="@android:color/transparent"
                        android:textColor="@color/colorLightText"
                        android:textSize="15sp" />

                    <ImageView
                        android:id="@+id/sharesImg"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_column="3"
                        android:layout_columnWeight="1"
                        android:layout_gravity="right|center_vertical"
                        android:layout_row="2"
                        android:background="@android:color/transparent"
                        android:scaleX="0.5"
                        android:scaleY="0.5"
                        app:srcCompat="@drawable/outline_assessment_black_36" />

                    <TextView
                        android:id="@+id/sharesTxt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_column="4"
                        android:layout_columnWeight="1"
                        android:layout_gravity="left|center_vertical"
                        android:layout_row="2"
                        android:background="@android:color/transparent"
                        android:textColor="@color/colorLightText"
                        android:textSize="15sp" />

                </GridLayout>

                <View
                    android:id="@+id/dividerMoney"
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/colorDivider"
                    app:layout_constraintTop_toBottomOf="@id/gridMoney" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="@dimen/recycler_horizontal_margin"
                    android:layout_marginStart="@dimen/recycler_horizontal_margin"
                    android:layout_marginTop="@dimen/activity_vertical_margin"
                    android:text="Aktien"
                    android:textColor="@color/colorPrimary"
                    android:textStyle="bold"
                    app:layout_constraintEnd_toEndOf="@+id/dividerMoney"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/gridMoney" />

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/recyclerShares"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="@dimen/recycler_title_bottom_margin"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/textView" />
            </LinearLayout>
        </android.support.v4.widget.NestedScrollView>
    </android.support.v4.widget.SwipeRefreshLayout>

</android.support.constraint.ConstraintLayout>

Upvotes: 4

Views: 579

Answers (2)

ʍѳђઽ૯ท
ʍѳђઽ૯ท

Reputation: 16976

Of course, setElevation(0); won't work.

But I still don't get why the method in onCreate() doesn't work.

AppbarLayout uses StateListAnimator from v24.0.0 and that is why setElevation will has no effect on it: https://stackoverflow.com/a/37992366/4409113

So:

StateListAnimator stateListAnimator = new StateListAnimator();
stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0));
appBarLayout.setStateListAnimator(stateListAnimator);

Or:

toolbarLayout = findViewById(R.id.abMainLayout); 
    toolbarLayout.StateListAnimator = null;

In your case.

Upvotes: 1

Chrobin
Chrobin

Reputation: 63

So @NileshRathod answered it:

It's app:elevation, not android:elevation. But I still don't get why the method in onCreate() doesn't work.

Upvotes: 2

Related Questions