listen for when the app goes compltely in the foreground and in the background

in app gradle:

//Lifecycles only (no ViewModel or LiveData) not working at the moment...
implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

create a class:

public class AppLifecycleObserver implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onMoveToForeground() {
        Log.d("AppLifecycleObserver", "Returning to foreground…");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onMoveToBackground() {
        Log.d("AppLifecycleObserver", "Moving to background…");
    }
}

 

initialize the AppLifecycleObserver in your app Application:

public class AppApplication extends Application {

    private AppLifecycleObserver appLifecycleObserver = new AppLifecycleObserver();

    @Override
    public void onCreate() {
        super.onCreate();
        setupLifecycleObserver();
    }

    private void setupLifecycleObserver() {
        ProcessLifecycleOwner
                .get()
                .getLifecycle()
                .addObserver(appLifecycleObserver);
    }
}

 

and finally, declare the AppApplication in the manifest

<application
    android:name=".AppApplication"

source: https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c

Fix RecyclerView not being smooth while inside a NestedScrollView

use

recyclerView.setNestedScrollingEnabled(false);
keep in mind this will cause the RecyclerView not to use the ViewHolder pattern. Use it when there aren’t a lot of items in it

.gitignore for android

Source: http://stackoverflow.com/a/21049338/2810172

# built application files
*.apk
*.ap_

# files for the dex VM
*.dex

# Java class files
*.class

# built native files (uncomment if you build your own)
# *.o
# *.so

# generated files
bin/
gen/

# Ignore gradle files
.gradle/
build/

# Local configuration file (sdk path, etc)
local.properties

# Proguard folder generated by Eclipse
proguard/

# Eclipse Metadata
.metadata/

# Mac OS X clutter
*.DS_Store

# Windows clutter
Thumbs.db

# Intellij IDEA (see https://intellij-support.jetbrains.com/entries/23393067)
.idea/workspace.xml
.idea/tasks.xml
.idea/datasources.xml
.idea/dataSources.ids

Renaming your android studio project

You can do this:

  1. Change the package name manually in the manifest file.
  2. Click on your R.java class and the press F6 (Refactor->Move…). It will allow you to move the class to another package, and all references to that class will be updated.

Source: http://stackoverflow.com/questions/6600329/how-do-i-rename-the-android-package-name

 

Other links that might be useful

http://stackoverflow.com/questions/16804093/android-studio-rename-package

http://stackoverflow.com/questions/18276872/change-project-name-on-android-studio

Previewing widgets in android studio preview mode

Inflating things this way seems to work for the preview:

public FlightOutboundInbound(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    setWeightSum(3);
    setBackgroundResource(R.drawable.dark_blue_border_rect);
    setOrientation(HORIZONTAL);

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.widget_flight_outbound_inbound, this, true);
    ButterKnife.bind(this);
}

But inflating things using the static view does not seem to work.

Source: http://stackoverflow.com/questions/17296552/preview-layout-with-merge-root-tag-in-intellij-idea-android-studio

<merge 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:parentTag="LinearLayout"
    tools:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some text"
        android:textSize="20sp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some other text"/>
</merge>

Changing Toolbar title styling

Source: http://stackoverflow.com/questions/26533510/android-toolbar-center-title-and-custom-font

The ToolBar title is stylable. Any customization you make has to be made in the theme. I’ll give you an example.

Toolbar layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    style="@style/ToolBarStyle.Event"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="@dimen/abc_action_bar_default_height_material" />

Styles:

<style name="ToolBarStyle" parent="ToolBarStyle.Base"/>

<style name="ToolBarStyle.Base" parent="">
    <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
    <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>

<style name="ToolBarStyle.Event" parent="ToolBarStyle">
    <item name="titleTextAppearance">@style/TextAppearance.Widget.Event.Toolbar.Title</item>
</style>

<style name="TextAppearance.Widget.Event.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <!--Any text styling can be done here-->
    <item name="android:textStyle">normal</item>
    <item name="android:textSize">@dimen/event_title_text_size</item>
</style>

 

variables in the local.properties file in android studio

local.properties file

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Mon Aug 22 10:54:33 BST 2016
sdk.dir=C\:\\Users\\MrDevMonk\\AppData\\Local\\Android\\Sdk
addsuffix=true

and then in the app gradle you can access it using the Properties class

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def addsuffix = properties.getProperty('addsuffix')

and you can also add it in the buildConfigField

buildConfigField "boolean", "ADD_SUFFIX", addsuffix

and from your hava classes you can access it:

BuildConfig.ADD_SUFFIX

EditText takes focus on activity start

Using android:focusableInTouchMode=”true” on the views that you don’t want to take focus automatically. It can also be applied only on the parent viewgroup of the edittexts.

 

Example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusableInTouchMode="true">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/msg_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/msg_input_remove_icon"
        android:layout_toStartOf="@+id/msg_input_remove_icon"
        android:hint="@string/message">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.design.widget.TextInputLayout>

    <ImageView
        android:id="@+id/msg_input_remove_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@android:drawable/ic_delete" />
</RelativeLayout>

 

Adding dividers to a RecyclerView and choosing which ones to show (Custom RecyclerView.ItemDecoration)

Most of the tutorials I found online say to override the “getItemOffsets” method and set the outRect.setEmpty(); on the view you don’t want a divider. This doesn’t seem to work, at least when using the “com.android.support:recyclerview-v7:25.3.1”.

To make it work i had to override the onDraw method. See below code for a custom  ItemDecoration class

 

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.ColorRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;

import uk.co.travelrepublic.travelrepublic.util.CompatUtil;

public class DividerItemDecorationWidget extends RecyclerView.ItemDecoration {
    private final Paint mPaint;

    public DividerItemDecorationWidget(Context context, @ColorRes int color, float heightDp) {
        mPaint = new Paint();
        mPaint.setColor(ContextCompat.getColor(context, color));
        final float thickness = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, heightDp, context.getResources().getDisplayMetrics());
        mPaint.setStrokeWidth(thickness);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        // we set the stroke width before, so as to correctly draw the line we have to offset by width / 2
        final int offset = (int) (mPaint.getStrokeWidth() / 2);

        // this will iterate over every visible view except the last one, we don't want a divider in the last view
        for (int i = 0; i < (parent.getChildCount() - 1); i++) {
            final View view = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();

            final int position = params.getViewAdapterPosition();

            if (position < state.getItemCount()) {
                c.drawLine(view.getLeft(), view.getBottom() + offset, view.getRight(), view.getBottom() + offset, mPaint);
            }
        }
    }
}

 

and if you want the divider lines to be drawn on top of the views (this is needed if you have a background color on the views, if this is not used then the divider lines will be hidden behind the background color)

 

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();

    // we want to retrieve the position in the list
    final int position = params.getViewAdapterPosition();

    // and add a separator to any view but the last one
    if (position < state.getItemCount()) {
        outRect.set(0, 0, 0, (int) mPaint.getStrokeWidth()); // left, top, right, bottom
    } else {
        outRect.setEmpty(); // 0, 0, 0, 0
    }
}

 

I got some ideas from David Medenjak blog post