how to get build/version code and name of your Android application android programmatically

Version your app

You can define default values for these settings by including them in the defaultConfig {} block, nested inside the android {} block of your module's build.gradle file. You can then override these default values for different versions of your app by defining separate values for individual build types or product flavors. The following build.gradle file shows the versionCode and versionName settings in the defaultConfig {} block, as well as the productFlavors {} block.

android {
  ...
  defaultConfig {
    ...
    versionCode 2
    versionName "1.1"
  }
  productFlavors {
    demo {
      ...
      versionName "1.1-demo"
    }
    full {
      ...
    }

versionCode

A positive integer used as an internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions.
The versionCode is integer value used to easily differentiate between new and old app versions. App developers must increment versionCode value when they release updates to their apps in Android Market, so it can determine if users are using an old version of the app, and offer them to update it.

versionName

A string used as the version number shown to users. This setting can be specified as a raw string or as a reference to a string resource. It is a string containing a regular “release version” as seen in other desktop applications, such as “1.4.5” or “3.7”. The versionName is just a “human readable” version code.


android get app version code programmatically

Check android version name for your application using below code like. Version 1.0 .
private String getApplicationVersion() {
            String versionStr;
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
            versionStr= "Version " + pInfo.versionName;
} catch (Exception e) {
            e.printStackTrace();
        }
return versionStr;
    }

Use the below function to get android app version code:
private String getApplicationVersionCode() {
            String verCode;
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
            int verCode = pInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
return verCode ;
    }

'versionCode' is deprecated as of API 28: Android 9.0 (Pie)


Android get screen width and height programmatically


Get bitmap from url android glide android

Get bitmap from Image using glide V4
Android  Code:
Glide.with(cxt)
  .asBitmap().load(imageUrl)
  .listener(new RequestListener<Bitmap>() {
      @Override
      public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Bitmap> target, boolean b) {
          Toast.makeText(cxt,getResources().getString(R.string.unexpected_error_occurred_try_again),Toast.LENGTH_SHORT).show();
          return false;
      }

      @Override
      public boolean onResourceReady(Bitmap bitmap, Object o, Target<Bitmap> target, DataSource dataSource, boolean b) {
          zoomImage.setImage(ImageSource.bitmap(bitmap));
          return false;
      }
  }
).submit();

Kotlin Code:
 Glide.with(this)
                .asBitmap().load("ImaegUrltODownload")
                .listener(object : RequestListener<Bitmap> {
                    override fun onResourceReady(
                            resource: Bitmap?,
                            model: Any?,
                            target: Target<Bitmap>?,
                            dataSource: DataSource?,
                            isFirstResource: Boolean
                    ): Boolean {

                        YourimageView.setImageBitmap(resource)

                        return false;
                    }

                    override fun onLoadFailed(
                            e: GlideException?,
                            model: Any?,
                            target: Target<Bitmap>?,
                            isFirstResource: Boolean
                    ): Boolean {
                        return false;
                    }
                }
                ).submit()

java.lang.NoClassDefFoundError Failed resolution of: Lorg/apache/http/ProtocolVersion Android (9) Pie

 I built App on Android studio targetSdkVersion 28 which targets Android P. The APK can be build ,but when I used it on device with OS Android (9) Pie, it throws below crash and see below detailed crash log for more details.

ANDROID CRASHLYTICS ERROR LOG:
Fatal Exception: java.lang.NoClassDefFoundError
Failed resolution of: Lorg/apache/http/ProtocolVersion;
com.google.android.gms.common.data.zac.b (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):3)
com.google.android.gms.common.data.zab.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):3)
com.google.android.gms.common.internal.AccountAccessor.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):19)
com.google.android.gms.ads.internal.util.aq.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):15)
com.google.android.gms.common.api.internal.TaskUtil.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):19)
com.google.android.gms.common.api.internal.TaskUtil.run (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):8)
Caused by java.lang.ClassNotFoundException
Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/user_de/0/com.google.android.gms/app_chimera/m/00000055/AdsDynamite.apk"],nativeLibraryDirectories=[/data/user_de/0/com.google.android.gms/app_chimera/m/00000055/AdsDynamite.apk!/lib/arm64-v8a, /system/lib64]]
dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:169)
java.lang.ClassLoader.loadClass (ClassLoader.java:379)
com.bumptech.glide.load.engine.EngineKeyFactory.loadClass (:com.google.android.gms.dynamite_dynamiteloader@14799081@14.7.99 (100400-223214910):4)
java.lang.ClassLoader.loadClass (ClassLoader.java:312)
com.google.android.gms.common.data.zac.b (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):3)
com.google.android.gms.common.data.zab.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):3)
com.google.android.gms.common.internal.AccountAccessor.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):19)
com.google.android.gms.ads.internal.util.aq.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):15)
com.google.android.gms.common.api.internal.TaskUtil.a (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):19)
com.google.android.gms.common.api.internal.TaskUtil.run (:com.google.android.gms.dynamite_adsdynamite@14799081@14.7.99 (100400-223214910):8)

SOLUTION:
This link android-9.0-changes-28-->Apache HTTP client deprecation explains reason for adding the following to your AndroidManifest.xml:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>

Similar errors : Need to specify requirement for Apache HTTP Legacy library
You can also face same error while using play-services-maps library. There are two solutions as below:

Solution 1: If you are working with com.google.android.gms:play-services-maps:16.0.0 or below then update the com.google.android.gms:play-services-maps library to the latest version. This is handled for you if you are using com.google.android.gms:play-services-maps:16.1.0 and is not necessary if your app is targeting a lower API level.
Or
Solution  2:  Include the below declaration within the <application> element of AndroidManifest.xml.
<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />
Refer the same included in the official docs: Specify requirement for Apache HTTP Legacy library
It's reported on issuetracker (Android bug tracker) :https://issuetracker.google.com/issues/79478779

More about Apache HTTP client deprecation:
With Android 6.0, we removed support for the Apache HTTP client. Beginning with Android 9, that library is removed from the bootclasspath and is not available to apps by default. To continue using the Apache HTTP client, apps that target Android 9 and above can add the following to their AndroidManifest.xml:
<uses-library android:name="org.apache.http.legacy" android:required="false">

Things to Note
 The android:required="false" attribute is required for apps that have a minimum SDK of 23 or lower, because on devices with API levels lower than 24, the org.apache.http.legacy library is not available. (On those devices, the Apache HTTP classes are available on the bootclasspath.) As an alternative to using the runtime Apache library, apps can bundle their own version of the org.apache.http library in their APK. If you do this, you must repackage the library (with a utility like Jar Jar) to avoid class compatibility issues with the classes provided in the runtime.

Fatal Exception: android.app.RemoteServiceException can't deliver broadcast

ANDROID App CRASH CRASHLYTICS LOG:
Fatal Exception: android.app.RemoteServiceException
can't deliver broadcast
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1867)
android.os.Handler.dispatchMessage (Handler.java:106)
android.os.Looper.loop (Looper.java:164)
android.app.ActivityThread.main (ActivityThread.java:6753)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:482)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807)
This error: android.app.remoteserviceexception android 8 was first visible on my App on device ONEPLUS A5000 with Android 8.1 Oreo

You can find the comment old code and the new added code from below snippet.

Send Broadcast(from Sender activity):
         try {
                                Intent broadcastIntent = new Intent();
                                broadcastIntent.setAction(mBroadcastStringAction);
//                                sendBroadcast(broadcastIntent);     //old code to send broadcast
   LocalBroadcastManager.getInstance(Application.get()).sendBroadcast(broadcastIntent);
                 }catch (Exception e){
                     e.printStackTrace();
                }

  Deceleration in Receiver Activity or fragment:
//declared the intent filter and the broadcast receiver instance
private IntentFilter mIntentFilter;
//Brroadcast-Action-String decleration
public static final String mBroadcastStringAction = "com.example.apppackage.broadcast.string";

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent!=null && intent.getAction().equals(mBroadcastStringAction)) {
                Log.e("BaseActivity","Your broadcast recived");
// set functionalities
      }
        }
    };

in onCreate of Receiver Activity or fragment:
//define the intent filter action
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(mBroadcastStringAction);
//register broadcast reciver
//        getActivity().registerReceiver(mReceiver, mIntentFilter);   // old code
        LocalBroadcastManager.getInstance(Application.get()).registerReceiver(mReceiver, mIntentFilter);

in OnPuase() method of Receiver Activity:
//unregister broadcast reciver
//        getActivity().unregisterReceiver(mReceiver); // old code
        LocalBroadcastManager.getInstance(Application.get()).unregisterReceiver(mReceiver);

To find more on LocalBroadcastManager Refer:
LocalBroadcastManager to send and receive broadcast in Android

RuntimeException: A TaskDescription's primary color should be opaque

Process: com.pit.pinkpepperz, PID: 27828
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.android/com.app.android.SplashActivity}: java.lang.RuntimeException: A TaskDescription's primary color should be opaque
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2487)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2547)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5604)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: java.lang.RuntimeException: A TaskDescription's primary color should be opaque
        at android.app.ActivityManager$TaskDescription.<init>(ActivityManager.java:617)
        at android.app.Activity.onApplyThemeResource(Activity.java:3836)
        at android.view.ContextThemeWrapper.initializeTheme(ContextThemeWrapper.java:150)
        at android.view.ContextThemeWrapper.setTheme(ContextThemeWrapper.java:94)
        at android.support.v7.app.AppCompatActivity.setTheme(AppCompatActivity.java:90)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2433)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2547)
        at android.app.ActivityThread.access$1100(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5604)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652) 

RuntimeException Unable to start activity ComponentInfo SignInHubActivity

Fatal Exception: java.lang.RuntimeException
Unable to start activity
ComponentInfo{com.example.demo.androidAppdemo/com.google.android.gms.auth.api.signin.
internal.SignInHubActivity}: java.lang.NullPointerException

android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2118)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2145)
android.app.ActivityThread.access$600 (ActivityThread.java:130)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1211)
android.os.Handler.dispatchMessage (Handler.java:99)
android.os.Looper.loop (Looper.java:137)
android.app.ActivityThread.main (ActivityThread.java:4847)
java.lang.reflect.Method.invokeNative (Method.java)
java.lang.reflect.Method.invoke (Method.java:535)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:786)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:553)
dalvik.system.NativeStart.main (NativeStart.java)

Caused by java.lang.NullPointerException
com.google.android.gms.auth.api.signin.internal.SignInHubActivity.onCreate (Unknown Source:9)
android.app.Activity.performCreate (Activity.java:5187)
android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1104)
android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2064)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2145)
android.app.ActivityThread.access$600 (ActivityThread.java:130)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1211)
android.os.Handler.dispatchMessage (Handler.java:99)
android.os.Looper.loop (Looper.java:137)
android.app.ActivityThread.main (ActivityThread.java:4847)
java.lang.reflect.Method.invokeNative (Method.java)
java.lang.reflect.Method.invoke (Method.java:535)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:786)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:553)
dalvik.system.NativeStart.main (NativeStart.java)

Android: how to hide progress bar in facebook login

After click of the Facebook login button, a progress bar appears with transparent background and then the Facebook activity opens.  How to disable/hide the progress circle at start of the facebook login.
I used the facebook sdk gradle version as below
implementation 'com.facebook.android:facebook-login:[4,5)'

and defined the Facebook activity in AndroidManifest.xml as suggested in the article Edit Your Resources and Manifest

 <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"

        android:label="@string/app_name" />

To remove indeterminate progress bar I followed link Android: How to hide progress circle in Facebook login

Define a new custom style in your /res/values/styles.xml as below

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

    <style name="Translucent.Base" parent="android:Theme.Translucent.NoTitleBar">
        <item name="android:progressBarStyle">@style/InvisibleProgress</item>
    </style>

Add above custom style to Facebook activity deceleration in AndroidManifest.xml
<activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@style/Translucent"
          />
Then try to run the Project
Gives error as below:
Manifest merger failed : Attribute activity#com.facebook.FacebookActivity@theme value=(@style/Translucent) from AndroidManifest.xml:294:13-47
is also present at [com.facebook.android:facebook-common:4.36.0] AndroidManifest.xml:32:13-63 value=(@style/com_facebook_activity_theme).
Suggestion: add 'tools:replace="android:theme"' to <activity> element at AndroidManifest.xml:290:9-295:15 to override.


tools:replace="android:theme"




Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable' on a null object reference

java.lang.RuntimeException: Unable to destroy activity
{com.example.demo.androidAppdemo/com.example.demo.androidAppdemo.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
        at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3945)
        at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3963)
        at android.app.ActivityThread.access$1700(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1454)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5604)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
        at com.example.demo.androidAppdemo.V2.NavigationDrawer.NavigationDrawerFragment$2.setResource(NavigationDrawerFragment.java:594)
        at com.example.demo.androidAppdemo.V2.NavigationDrawer.NavigationDrawerFragment$2.setResource(NavigationDrawerFragment.java:588)
        at com.bumptech.glide.request.target.ImageViewTarget.setResourceInternal(ImageViewTarget.java:127)
        at com.bumptech.glide.request.target.ImageViewTarget.onLoadCleared(ImageViewTarget.java:97)
        at com.bumptech.glide.request.SingleRequest.clear(SingleRequest.java:319)
        at com.bumptech.glide.manager.RequestTracker.clearRemoveAndMaybeRecycle(RequestTracker.java:79)
        at com.bumptech.glide.manager.RequestTracker.clearRemoveAndRecycle(RequestTracker.java:66)
        at com.bumptech.glide.RequestManager.untrack(RequestManager.java:603)
        at com.bumptech.glide.RequestManager.untrackOrDelegate(RequestManager.java:571)
        at com.bumptech.glide.RequestManager.clear(RequestManager.java:559)
        at com.bumptech.glide.RequestManager.onDestroy(RequestManager.java:303)
        at com.bumptech.glide.manager.ActivityFragmentLifecycle.onDestroy(ActivityFragmentLifecycle.java:65)
        at com.bumptech.glide.manager.SupportRequestManagerFragment.onDestroy(SupportRequestManagerFragment.java:194)
        at android.support.v4.app.Fragment.performDestroy(Fragment.java:2588)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1566)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3244)
        at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:3235)
        at android.support.v4.app.Fragment.performDestroy(Fragment.java:2583)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1566)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3244)
        at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:3235)
        at android.support.v4.app.FragmentController.dispatchDestroy(FragmentController.java:265)
        at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:390)
        at android.support.v7.app.AppCompatActivity.onDestroy(AppCompatActivity.java:209)
        at com.example.demo.androidAppdemo.BaseActivity.onDestroy(BaseActivity.java:867)
        at com.example.demo.androidAppdemo.MainActivity.onDestroy(MainActivity.java:783)
        at android.app.Activity.performDestroy(Activity.java:6529)
    at android.app.Instrumentation.callActivityOnDestroy(

Above error thrown while closing app-BaseActivity is being destroyed. Getting this error while setting the Profile Photo of user in the navigation drawer fragment. This error is thrown when closing the app just after app starts. This error is being thrown in the below code while setting image using setImageDrawable after the converting the image to circular image using the RoundedBitmapDrawableFactory and using Glide V4.

 GlideApp.with(NavigationDrawerFragment.this).asBitmap().load(profilePhotoUrl).centerCrop().into(new BitmapImageViewTarget(navigation_header_splash_icon) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
  RoundedBitmapDrawableFactory.create(NavigationDrawerFragment.this.getResources(),resource);
                        circularBitmapDrawable.setCircular(true);
//getting error in below line
                        navigation_header_splash_icon.setImageDrawable(circularBitmapDrawable);
                    }
                });

Replace the above
    GlideApp.with(NavigationDrawerFragment.this)
                        .asBitmap()
                        .load(profilePhotoUrl)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .error(R.drawable.splash_icon)
                        .placeholder(R.drawable.splash_icon)
                        .transforms(new RoundedCorner( Application.get(),dpToPx(75/2), 1))
                        .into(navigation_header_splash_icon);

or Use glide V 4 library RequestOptions to crop the image to circular image
Glide.with(NavigationDrawerFragment.this)
        .load(profilePhotoUrl)
        .apply(RequestOptions.circleCropTransform())
        .into(navigation_header_splash_icon);

Glide v4: Glide treats LayoutParams.WRAP_CONTENT as a request for an image the size of this device's screen

10-13 12:56:00.395 2255-2255/com.example.demo.androidAppdemo
I/ViewTarget: Glide treats LayoutParams.WRAP_CONTENT as a request for
an image the size of this device's screen dimensions. If you want to load
the original image and are ok with the corresponding memory cost and OOMs
(depending on the input size), use .override(Target.SIZE_ORIGINAL).

Otherwise, use LayoutParams.MATCH_PARENT,
set layout_width and layout_height to fixed dimension,
or use .override() with fixed dimensions.

How to change the shape stroke color android programmatically

To set the shape stroke color programmatically this example uses GradientDrawable method setStroke(int width, int color) which sets the stroke width and change shape's color. Here default orange color of the shape drawable is changes programetically usingb GradientDrawable method setStroke(int width, int color).

GradientDrawable

A GradientDrawable is Drawable with a color gradient for buttons, backgrounds, etc.
It can be defined in an XML file with the <shape> element. For more information, see GradientDrawable.

res/drawable/stroke_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="@android:color/transparent" />

    <stroke
        android:width="3dp"
        android:color="@android:color/holo_orange_dark" />

    <corners
    android:bottomRightRadius="10dp"
    android:bottomLeftRadius="10dp"
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp"/>
</shape>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="quizcounter.compete.geeks.vectordrawablecolorchange.MainActivity">

    <Button
        android:layout_marginTop="10dp"
        android:id="@+id/button"
        android:text="Change Stroke Color"
        android:layout_width="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView "
        android:padding="10dp"
        android:textColor="@android:color/black"
        android:background="@drawable/stroke_background"
         />

</LinearLayout>

MainActivity.java
package quizcounter.compete.geeks.shapestrokecolorchange;

import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=findViewById(R.id.text);
        button=findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               //To change the stroke color
                GradientDrawable myGrad = (GradientDrawable)textView.getBackground();
                myGrad.setStroke(convertDpToPx(3), Color.RED);
            }
        });
    }

    private int convertDpToPx(int dp){
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }
}



How to change color of vector drawable path android programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="quizcounter.compete.geeks.vectordrawablecolorchange.MainActivity">

    <Button
        android:layout_marginTop="10dp"
        android:id="@+id/button"
        android:text="Change Color"
        android:layout_width="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:drawableRight="@drawable/ic_settings_black_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>
MainActivity.java

package quizcounter.compete.geeks.vectordrawablecolorchange;

import android.graphics.drawable.Drawable;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=findViewById(R.id.text);
        button=findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

               // Take vector drawable you want to set to textview
                Drawable vectorDrawable = VectorDrawableCompat.create(
                        getResources(),
                        R.drawable.ic_settings_black_24dp,
                        null);
                Drawable drawable = DrawableCompat.wrap(vectorDrawable);

               // Change color o Vector drawable to colorAssent                 DrawableCompat.setTint(drawable.mutate(),getResources().getColor(R.color.colorAccent));

               //set vector as right drawable
                textView.setCompoundDrawablesWithIntrinsicBounds(null, null,drawable, null);

                textView.setTextColor(getResources().getColor(R.color.colorAccent));
            }
        });


    }
}



Android Fatal Exception: java.lang.NoSuchFieldError

Fatal Exception: java.lang.NoSuchFieldError
       at libcore.reflect.AnnotationAccess.decodeValue(AnnotationAccess.java:688)
       at libcore.reflect.AnnotationAccess.getDefaultValue(AnnotationAccess.java:361)
       at java.lang.reflect.Method.getDefaultValue(Method.java:327)
       at libcore.reflect.AnnotationFactory.getElementsDescription(AnnotationFactory.java:75)
       at libcore.reflect.AnnotationFactory.(AnnotationFactory.java:112)
       at libcore.reflect.AnnotationFactory.createAnnotation(AnnotationFactory.java:94)
       at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:666)
       at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:641)
       at libcore.reflect.AnnotationAccess.getDeclaredAnnotation(AnnotationAccess.java:170)
       at java.lang.reflect.Field.getAnnotation(Field.java:252)
       at com.j256.ormlite.field.DatabaseFieldConfig.getFieldName(Unknown Source)
       at com.j256.ormlite.android.DatabaseTableConfigUtil.fromClass(Unknown Source)
       at com.j256.ormlite.android.DatabaseTableConfigUtil.fromClass(Unknown Source)
       at com.j256.ormlite.db.SqliteAndroidDatabaseType.getFieldConverter(Unknown Source)
       at com.j256.ormlite.dao.DaoManager.createDao(Unknown Source)
       at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.onCreate(Unknown Source)
       at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.getRuntimeExceptionDao(Unknown Source)
       at com.elitech.offers.coupons.deals.DataBase.DatabaseHelper.onCreate(Unknown Source)
       at com.elitech.offers.coupons.deals.DataBase.dbGetData.CheckIdExist(Unknown Source)
       at com.elitech.offers.coupons.deals.SplashScreenActivity.getUpdatedDateCategories(Unknown Source)
       at com.elitech.offers.coupons.deals.SplashScreenActivity.getData(Unknown Source)
       at com.elitech.offers.coupons.deals.SplashScreenActivity.onRequestPermissionsResult(Unknown Source)
       at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:6688)
       at android.app.Activity.dispatchActivityResult(Activity.java:6566)
       at android.app.ActivityThread.deliverResults(ActivityThread.java:3768)
       at android.app.ActivityThread.handleSendResult(ActivityThread.java:3815)
       at android.app.ActivityThread.access$1500(ActivityThread.java:154)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:157)
       at android.app.ActivityThread.main(ActivityThread.java:5571)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)

Caused by java.lang.NoSuchFieldException: No field UNKNOWN in class Lcom/c/a/d/d;
(declaration of 'com.c.a.d.d' appears in /data/app/com.elitech.offers.coupons.deals-1/base.apk)

       at java.lang.Class.getDeclaredField(Class.java)
       at libcore.reflect.AnnotationAccess.decodeValue(AnnotationAccess.java:685)
       at libcore.reflect.AnnotationAccess.getDefaultValue(AnnotationAccess.java:361)
       at java.lang.reflect.Method.getDefaultValue(Method.java:327)
       at libcore.reflect.AnnotationFactory.getElementsDescription(AnnotationFactory.java:75)
       at libcore.reflect.AnnotationFactory.(AnnotationFactory.java:112)
       at libcore.reflect.AnnotationFactory.createAnnotation(AnnotationFactory.java:94)
       at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:666)
       at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:641)
       at libcore.reflect.AnnotationAccess.getDeclaredAnnotation(AnnotationAccess.java:170)
       at java.lang.reflect.Field.getAnnotation(Field.java:252)
       at com.j256.ormlite.field.DatabaseFieldConfig.getFieldName(Unknown Source)
       at com.j256.ormlite.android.DatabaseTableConfigUtil.fromClass(Unknown Source)
       at com.j256.ormlite.android.DatabaseTableConfigUtil.fromClass(Unknown Source)
       at com.j256.ormlite.db.SqliteAndroidDatabaseType.getFieldConverter(Unknown Source)
       at com.j256.ormlite.dao.DaoManager.createDao(Unknown Source)
       at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.onCreate(Unknown Source)
       at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.getRuntimeExceptionDao(Unknown Source)
       at com.elitech.offers.coupons.deals.DataBase.DatabaseHelper.onCreate(Unknown Source)
       at com.elitech.offers.coupons.deals.DataBase.dbGetData.CheckIdExist(Unknown Source)
       at com.elitech.offers.coupons.deals.SplashScreenActivity.getUpdatedDateCategories(Unknown Source)
       at com.elitech.offers.coupons.deals.SplashScreenActivity.getData(Unknown Source)
       at com.elitech.offers.coupons.deals.SplashScreenActivity.onRequestPermissionsResult(Unknown Source)
       at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:6688)
       at android.app.Activity.dispatchActivityResult(Activity.java:6566)
       at android.app.ActivityThread.deliverResults(ActivityThread.java:3768)
       at android.app.ActivityThread.handleSendResult(ActivityThread.java:3815)
       at android.app.ActivityThread.access$1500(ActivityThread.java:154)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:157)
       at android.app.ActivityThread.main(ActivityThread.java:5571)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)

Change the font of tab text in android TabLayout programetically



 res/layout/activity_main.xml
<? 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:layout_width="match_parent"
    android:layout_height="match_parent" >

    <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"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        android:layout_gravity="bottom"   >
    </android.support.design.widget.TabLayout>
   </android.support.v4.view.ViewPager>
</ android.support.constraint.ConstraintLayout>


MainActivity.java
package com.example.geekscompete.tablayouttextfontdemo;

import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    TabLayout tabs;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=findViewById(R.id.viewpager);
        tabs=findViewById(R.id.tabs);

        tabs.addTab(tabs.newTab().setText("Tab 1"));
        tabs.addTab(tabs.newTab().setText("Tab 2"));
        tabs.addTab(tabs.newTab().setText("Tab 3"));
        tabs.setTabTextColors(getResources().getColor(R.color.lime),getResources().getColor(R.color.colorAccent));
        changeTabsFont();
}
    private void changeTabsFont() {
      ViewGroup childTabLayout = (ViewGroup) tabs.getChildAt(0);
      for (int i = 0; i < childTabLayout.getChildCount(); i++) {
        ViewGroup viewTab = (ViewGroup) childTabLayout.getChildAt(i);
        for (int j = 0; j < viewTab.getChildCount(); j++) {
          View tabTextView = viewTab.getChildAt(j);
          if (tabTextView instanceof TextView) {
            Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Regular.ttf");
            ((TextView) tabTextView).setAllCaps(false);
            ((TextView) tabTextView).setTypeface(typeface);
         }
        }
      }
    }
}

android change tablayout text color programmatically


 res/layout/activity_main.xml
<? 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:layout_width="match_parent"
    android:layout_height="match_parent" >

    <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/tablayout"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        android:layout_gravity="bottom"   >
    </android.support.design.widget.TabLayout>
   </android.support.v4.view.ViewPager>
</ android.support.constraint.ConstraintLayout>


MainActivity.java
package com.example.geekscompete.tablayouttextcolordemo;

import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=findViewById(R.id.viewpager);
        tabLayout=findViewById(R.id.tablayout);

        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabTextColors(getResources().getColor(R.color.lime),getResources().getColor(R.color.colorAccent));
    }
}

android DeadSystemException

Found this crash log on Crashlytics with first time on Android 8.0 Samsung device.
# OS Version: 8.0.0
# Device: SM-A605G
Fatal Exception: java.lang.RuntimeException: android.os.DeadSystemException
       at android.app.ActivityThread.handleSleeping(ActivityThread.java:4405)
       at android.app.ActivityThread.-wrap23(Unknown Source)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1893)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:164)
       at android.app.ActivityThread.main(ActivityThread.java:6944)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Caused by android.os.DeadSystemException
       at android.app.ActivityThread.handleSleeping(ActivityThread.java:4405)
       at android.app.ActivityThread.-wrap23(Unknown Source)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1893)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:164)
       at android.app.ActivityThread.main(ActivityThread.java:6944)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

#0. Crashed: main
       at android.app.ActivityThread.handleSleeping(ActivityThread.java:4405)
       at android.app.ActivityThread.-wrap23(Unknown Source)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1893)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:164)
       at android.app.ActivityThread.main(ActivityThread.java:6944)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

#1. Queue
       at java.lang.Object.wait(Object.java)
       at java.lang.Thread.parkFor$(Thread.java:2135)
       at sun.misc.Unsafe.park(Unsafe.java:358)
       at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
       at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
       at java.util.concurrent.PriorityBlockingQueue.take(PriorityBlockingQueue.java:548)
       at io.fabric.sdk.android.services.concurrency.DependencyPriorityBlockingQueue.performOperation(DependencyPriorityBlockingQueue.java:197)
       at io.fabric.sdk.android.services.concurrency.DependencyPriorityBlockingQueue.get(DependencyPriorityBlockingQueue.java:236)
       at io.fabric.sdk.android.services.concurrency.DependencyPriorityBlockingQueue.take(DependencyPriorityBlockingQueue.java:65)
       at io.fabric.sdk.android.services.concurrency.DependencyPriorityBlockingQueue.take(DependencyPriorityBlockingQueue.java:46)
       at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1087)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1147)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
       at java.lang.Thread.run(Thread.java:764)

#2. AdWorker(Default) #8
       at java.lang.Object.wait(Object.java)
       at java.lang.Thread.parkFor$(Thread.java:2135)
       at sun.misc.Unsafe.park(Unsafe.java:358)
       at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
       at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:459)
       at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
       at java.util.concurrent.SynchronousQueue.take(SynchronousQueue.java:920)
       at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1087)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1147)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
       at java.lang.Thread.run(Thread.java:764)

#3. Loader:ExtractorSampleSource
       at java.lang.Object.wait(Object.java)
       at java.lang.Thread.parkFor$(Thread.java:2135)
       at sun.misc.Unsafe.park(Unsafe.java:358)
       at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
       at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
       at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
       at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1087)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1147)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
       at java.lang.Thread.run(Thread.java:764)

#4. fifo-pool-thread-5
       at java.lang.Object.wait(Object.java)
       at java.lang.Thread.parkFor$(Thread.java:2135)
       at sun.misc.Unsafe.park(Unsafe.java:358)
       at java.util.concurrent.locks.LockSupport.park(LockSupport.java:190)
       at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2059)
       at java.util.concurrent.PriorityBlockingQueue.take(PriorityBlockingQueue.java:548)
       at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1087)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1147)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
       at java.lang.Thread.run(Thread.java:764)
       at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)

android image slider with indicator using ViewPager and Tablayout

 res/layout/activity_main.xml
<? 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:layout_width="match_parent"
    android:id="@+id/constraintLayout"
    android:layout_height="match_parent"
    android::background="@color/white"
    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/tablayout"
        app:tabTextColor="@color/white"
        app:tabSelectedTextColor="@color/colorAccent"
        app:tabIndicatorColor="@color/colorAccent"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        android:layout_gravity="bottom">
        app:tabGravity="center">
        app:tabPaddingEnd="0dp">
        app:tabPaddingStart="0dp">
        app:tabIndicatorHeight="0dp">
        android:background="@android:color/transparent">
    </android.support.design.widget.TabLayout>

   </android.support.v4.view.ViewPager>
</ android.support.constraint.ConstraintLayout>

 res/layout/slider_imageview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imageView"
    android:scaleType="fitXY"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BlankFragment">

</ImageView>

ViewPagerAdapter.java
package com.example.geekscompete.tablayouttextcolordemo;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import import android.widget.ImageView;
import import android.view.View;
import import android.view.ViewGroup;

public class ViewPagerAdapter extends PagerAdapter {

    private Context mContext;
    private Integer [] slider_images={R.drawable.slider_image1,R.drawable.slider_image2,R.drawable.slider_image3};

    public ViewPagerAdapter(Context context) {this.mContext=context; }
    // This determines the number of tabs
    @Override
    public int getCount() {
    return slider_images.length;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
    View itemView = LayoutInflater.from(mContext).inflate(R.layout.slider_imageview_layout, container, false);
    ImageView imageView = itemView.findViewById(R.id.imageView);
    imageView.setImageResource(slider_images[position]);
    container.addView(itemView,position);
    return itemView;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
    return view == object; }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    ViewPager vp = (ViewPager) container;
    View view = (View) object;
    vp.removeView(view);
   }
   }

 res/drawable/selected_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:useLevel="true"
    android:dither="true">
<size android:height="12dip" android:width="12dip" />
<solid android:color="@color/silver"/>
</shape>


 res/drawable/selected_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    android:useLevel="true"
    android:dither="true">
<size android:height="12dip" android:width="12dip" />
<solid android:color="@color/black"/>
</shape>


 res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="silver">#C0C0C0</color>
    <color name="black">#000000</color>
</resources>


MainActivity.java
package com.example.geekscompete.tablayouttextcolordemo;

import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=findViewById(R.id.viewpager);
        tabLayout=findViewById(R.id.tablayout);

        viewPager.setAdapter(new ViewPagerAdapter(this));
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).setIcon(R.drawable.selected_dot);
        tabLayout.getTabAt(1).setIcon(R.drawable.unselected_dot);
        tabLayout.getTabAt(2).setIcon(R.drawable.unselected_dot);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
        tabLayout.getTabAt(tab.getPosition()).setIcon(R.drawable.selected_dot);
       }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            tabLayout.getTabAt(tab.getPosition()).setIcon(R.drawable.unselected_dot);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
       });
    }
}


Android Tablayout With ViewPager, Fragments And Constraint layout

 res/layout/activity_main.xml
<? 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:layout_width="match_parent"
    android:id="@+id/constraintLayout"
    android:layout_height="match_parent"
    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/tablayout"
        app:tabTextColor="@color/white"
        app:tabSelectedTextColor="@color/colorAccent"
        app:tabIndicatorColor="@color/colorAccent"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        android:layout_gravity="bottom">
    </android.support.design.widget.TabLayout>
   </android.support.v4.view.ViewPager>
</ android.support.constraint.ConstraintLayout>

 res/layout/fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    tools:context=".BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <android.support.v7.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="1" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="2" />

        <!-- TextViews from 3-13 -->

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="14" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="1" />

        <!-- TextViews from 2-19 -->
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="20" />

    </android.support.v7.widget.LinearLayoutCompat>
    </ScrollView>
</FrameLayout>

ViewPagerFragmentAdapter .java
package com.example.geekscompete.tablayouttextcolordemo;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.SparseArray;

public class ViewPagerFragmentAdapter extends FragmentPagerAdapter {

    private SparseArray<Fragment> childFragments=new SparseArray<>();
    private String titles[] = {"ONE","TWO","THREE"};

    public ViewPagerFragmentAdapter(FragmentManager fm) {
        super(fm);
        childFragments.put(0, new BlankFragment());
        childFragments.put(1, new BlankFragment());
        childFragments.put(2, new BlankFragment());
    }

    // This determines the fragment for each tab
    @Override
    public Fragment getItem(int position) {
    return childFragments.get(position);
    }

    // This determines the number of tabs
    @Override
    public int getCount() {
    return childFragments.size();
    }

    // This determines the title for each tab
    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        switch (position) {
            case 0:
                return titles[0];
            case 1:
                return titles[1];
            case 2:
                return titles[2];
            default:
                return null;
        }
    }
}

MainActivity.java
package com.example.geekscompete.tablayouttextcolordemo;

import android.graphics.Color;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=findViewById(R.id.viewpager);
        tabLayout=findViewById(R.id.tablayout);

        viewPager.setAdapter(new ViewPagerFragmentAdapter(getSupportFragmentManager()));
        tabLayout.setupWithViewPager(viewPager);
    }
}

android:layout_gravity="top"
android:layout_gravity="bottom"


Popular Posts