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