Saturday, September 30, 2017

android - Create view with style resource

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"
    android:id="@+id/base_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#abb49b"
    android:padding="16dp"
    >
    <Button
        android:id="@+id/btn_do_task"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add New TextView"
        android:layout_gravity="center_horizontal"
        />
</LinearLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private LinearLayout mBaseLayout;
    private Button mBtnDoTask;

    private int mCounter = 1;

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

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widgets reference from xml layout
        mBaseLayout = findViewById(R.id.base_layout);
        mBtnDoTask = findViewById(R.id.btn_do_task);


        // Set a click listener for button widget
        mBtnDoTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Create a new text view with style resource and add it to layout
                addTextViewToLayout("TextView : " + mCounter);

                // Increment the counter
                mCounter++;
            }
        });
    }


    // Custom method to create a new text view with style resource and add it to layout
    protected void addTextViewToLayout(String text){
        // Count the base layout child views
        int childCounter = mBaseLayout.getChildCount();

        // Define the style for current text view
        int themeResourceId = R.style.TextViewStyle;
        if(childCounter%2 == 0){
            themeResourceId = R.style.TextViewAltStyle;
        }

        /*
            ContextThemeWrapper
               A context wrapper that allows you to modify or replace the theme
               of the wrapped context.
        */

        /*
            ContextThemeWrapper (Context base, int themeResId)
                Creates a new context wrapper with the specified theme.

                The specified theme will be applied on top of the base context's theme.
                Any attributes not explicitly defined in the theme identified by themeResId
                will retain their original values.

            Parameters
                base Context : the base context
                themeResId int : the resource ID of the theme to be applied on top of
                                 the base context's theme
        */

        // Initialize a new text view
        TextView tv = new TextView(
                new ContextThemeWrapper(
                        mActivity,
                        themeResourceId
                )
        );

        // Initialize a new layout parameter
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);

        // Add layout parameter to text view
        tv.setLayoutParams(params);

        // Set the text for text view
        tv.setText(text);

        // Finally, add the text view to layout
        mBaseLayout.addView(tv);
    }
}
res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <!-- Important for toolbar  -->
        <item name="windowNoTitle">false</item>
    </style>

    <style name="TextViewStyle">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">#ff0967</item>
        <item name="android:background">#fcceff</item>
        <item name="android:textStyle">bold</item>
        <item name="android:padding">10dp</item>
    </style>

    <style name="TextViewAltStyle" parent="TextViewStyle">
        <item name="android:textColor">#2a4a83</item>
        <item name="android:background">#8cd0e6</item>
        <item name="android:textStyle">italic</item>
    </style>

</resources>