Android EditText Koltin

In Android EditText is user interface for entering and modifying text , when using you must specify the type of data that EditText accept  using  android:inputType .



Project Detail
Project Name AndroidEditText
Package com.tutorialsbuzz.androidedittext
Min Sdk Version 22
Target Sdk Version 28
Compile Sdk Version 28
Theme Theme.AppCompat.Light.DarkActionBar

1. gradle


file : build.gradle (Application Level Gradle)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.tutorialsbuzz.androidedittext"
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}


2. XML Layout


file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity"
        android:gravity="center"
        android:padding="10dp"
        android:id="@+id/rootLayout">

    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_text"
            android:id="@+id/editText"
            android:maxLines="1"
            android:imeOptions="actionDone"
            android:inputType="text"
            android:padding="10dp"
    />

</LinearLayout>


  • android:inputType : value of this attribute aspecifies the type of data that edittext accepts 
              here are all the possible values of android:inputType
  1. none
  2. text
  3. textCapCharacters
  4. textCapWords
  5. textCapSentences
  6. textAutoCorrect
  7. textAutoComplete
  8. textMultiLine
  9. textImeMultiLine
  10. textNoSuggestions
  11. textUri
  12. textEmailAddress
  13. textEmailSubject
  14. textShortMessage
  15. textLongMessage
  16. textPersonName
  17. textPostalAddress
  18. textPassword
  19. textVisiblePassword
  20. textWebEditText
  21. textFilter
  22. textPhonetic
  23. textWebEmailAddress
  24. textWebPassword
  25. number
  26. numberSigned
  27. numberDecimal
  28. numberPassword
  29. phone
  30. datetime
  31. date
  32. time

  • android:maxLines : Set Number of lines user can input
Note : You just need to make sure you have the attribute "android:inputType" set. It doesn't work without inputType.
  • android:hint Show hint text 

EditText on Editor Change Listener


android:imeOptions this attribute takes keyboard action as value
for example if you want to recognize when action DONE button has clicked ,

  1.  android:imeOptions attribute equal to “actionDone” ,
  2.  Set Editor Change Listener on EditText , override onEditorAction method To Recognize Action DONE.  
 editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Toast.makeText(this@MainActivity, "You Have Entered: " + editText.text.toString(), Toast.LENGTH_SHORT)
                    .show()
                false
            } else {
                false
            }
        }

EditText on TextChange Listener

  1. TextChangeListener monitor whenever there is change of text in EditText
  2. TextChangeListener interface has 3 method afterTextChanged , beforeTextChanged , onTextChanged 

editText.addTextChangedListener(object : TextWatcher {
 override fun afterTextChanged(s: Editable?) {
  Log.d(TAG, "afterTextChanged: " + s.toString());
 }

 override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
  Log.d(TAG, "beforeTextChanged: " + s.toString());
 }

 override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
  Log.d(TAG, "onTextChanged: " + s.toString());
 }
})


3. Activity


file : MainActivity.kt
package com.tutorialsbuzz.androidedittext

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    val TAG: String = "MainActivity";

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //EditText on Editor Change Listener
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Toast.makeText(this@MainActivity, "You Have Entered: " + editText.text.toString(), Toast.LENGTH_SHORT)
                    .show()
                false
            } else {
                false
            }
        }

        //EditText on TextChange Listener
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                Log.d(TAG, "afterTextChanged: " + s.toString());
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                Log.d(TAG, "beforeTextChanged: " + s.toString());
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Log.d(TAG, "onTextChanged: " + s.toString());
            }
        })

    }
}


Read More »

Android Table Layout Example

Android TableLayout as the name suggest it arranges the child views in rows and columns , just like standard HTML Table tag .

In this tutorial we will see an example of designing login screen using table layout that contains edittext ,textview and button.



Lets See An Example

Project Detail
Project Name DynamicTableLayout
Package com.pavan.dynamictablelayout
Minimum SDK API 8
Target SDK API 17
Theme Holo Light with Dark Action Bar

1. XML Layout


file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:shrinkColumns="*"
    android:stretchColumns="*" >

    <!-- Row1 Column1 -->

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" >

        <TextView
            android:id="@+id/textView9"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Login"
            android:textSize="24dp"
            android:textStyle="bold" >
        </TextView>
    </TableRow>

    <!-- Row2 Column2 -->

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="UserName"
            android:textSize="16dp" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10" >
        </EditText>
    </TableRow>

    <!-- Row3 Column3 -->

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password"
            android:textSize="16dp" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword" >
        </EditText>
    </TableRow>

    <!-- Row4 Column1 -->

    <TableRow
        android:id="@+id/tableRow4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right" >

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SignIn" />
    </TableRow>

</TableLayout>

2. Activity


file : MainActivity.java
package com.pavan.tablelayoutdemo;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}



3. RUN





Read More »

Android System Date And Time In Different Format

There are many different formats of displaying date and time  , In this tutorial we will see how to show system date and time in different format  inside your android application .





we use make use of Calender class of java.util package , the static method getInstance of Calender class returns the  instance of Calender and this object can produce all the time field values  needed to implement the date-time format

 Calendar c = Calendar.getInstance();

After getting calendar Instance , we required a formatted object for date and time.

The SimpleDateFormat Class is used for setting the format , the constructor of this class takes the pattern describing what strings are to produced

SimpleDateFormat format = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss ");
String formatdate=format(c.getTime());


file : activity_main.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="22sp" />

</RelativeLayout>

file : MainActivity
package com.example.sysdatetime;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView tv;
 Button btn;

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

  tv = (TextView) findViewById(R.id.display);

  Calendar c = Calendar.getInstance();

  SimpleDateFormat format1, format2, format3, format4, format5;

  format1 = new SimpleDateFormat("dd:MM:yyyy:HH:mm:ss ");

  format2 = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");

  format3 = new SimpleDateFormat("dd-MMMM-yyyy-HH-mm-ss");

  format4 = new SimpleDateFormat("dd/MMM/yyyy/HH/mm/ss");

  format5 = new SimpleDateFormat("dd_MM_yy_HH_mm_ss a");

  tv.setText(format1.format(c.getTime()) + "nn"
    + format2.format(c.getTime()) + "nn"
    + format3.format(c.getTime()) + "nn"
    + format4.format(c.getTime()) + "nn"
    + format5.format(c.getTime()));

 }
}


In this below table you can see the patterns description for date time and also the separator which is used for formatting.

Date format
Date FormatDescriptionValue
dSingle digit date eg 11
dddouble digit date eg 0101
MSingle digit month eg: 11
MMDouble digit month eg: 0101
MMMthree letter abbreviation for month ex: janjan
MMMMmonth spelled out in full ex : januaryjanuary
yydouble digit year ex : 1414
yyyyfour digit year ex : 20142014


Time Format
Time FormatDescriptionValue
hsingle digit hours in 12hours format9
hhdouble digit hours in 12 hour format09
Hsingle digit hours in 24 hour format8AM as 8
8PM as 20
HHdouble digit hours in 24 hour format8AM as 08
8PM as 20
msingle digit minute9
mmdouble digit minute09
ssingle digit second9
ssdouble digit second09
aMarkeram/pm


Separator
FormatDescription
" . "Dots or full stops
" _ "Hyphens or dashes
" " Spaces
" : "colon mostly used between time
" / "Slash

Read More »

Android Button State Change Example

Android Button represents a push button and it is a sub class TextView ,In this post we will see how to decorate default button widget by add drawable xml resource which performs state change of button i.e ( focused , pressed )


Drawable Resource XML


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

    <gradient
        android:angle="270"
        android:endColor="#2f6699"
        android:startColor="#449def" />

    <stroke
        android:width="1dp"
        android:color="#2f6699" />

    <corners android:radius="4dp" />

    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />

</shape>

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

    <corners android:radius="14dp" />

    <solid android:color="#6B7FFF" />

    <padding
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp" />

    <size
        android:height="60dp"
        android:width="270dp" />

</shape>

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

    <corners android:radius="14dp" />

    <gradient
        android:angle="45"
        android:centerColor="#386AE0"
        android:centerX="35%"
        android:endColor="#2F7999"
        android:startColor="#36EBFF"
        android:type="linear" />

    <padding
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp" />

    <size
        android:height="60dp"
        android:width="270dp" />

</shape>


file : buttonselector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

     <item android:drawable="@drawable/button_default"></item>

    <item android:drawable="@drawable/button_pressed"
               android:state_pressed="true">
    </item>

    <item android:drawable="@drawable/button_focused"  
               android:state_focused="true">
    </item>

</selector>


Main XML Layout


 file : activity_main.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="181dp"
        android:background="@drawable/buttonselector"
        android:text="Button"
        android:textColor="#ffffff"
        android:textSize="25dp" />

</RelativeLayout>


Main Activity


file : MainActivity.java
package com.pavan.buttonstatedemo;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

}



Read More »

Check Android ScreenOrientation At Runtime

In this Post we will see how to check android screen-orientation at Run-time , in the previous series i have covered how to fixed the Activity (Screen) to any particular orientation (i.e either Landscape or Portrait ) .
Android Portrait Mode Android LandScape Mode


  1. Firstly we will get the Resources object of application and.
  2. Then we will get the configuration object that is in effect with resource object  .
  3. The configuration class contains a constants whose values may be one of ORIENTATION_LANDSCAPE, ORIENTATION_PORTRAIT. using this constant we will get to know what is the current orientation.

Resources res = getResources();
Configuration conf = res.getConfiguration();

int flag = conf.orientation;


1. XML Layout


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text=""
        android:textSize="25sp" />

</LinearLayout>

2. Activity


package com.pavan.screenorientationdemo;

import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView display;

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

  display = (TextView) findViewById(R.id.textView1);

  Resources res = getResources();
  Configuration conf = res.getConfiguration();

  int flag = conf.orientation;

  if (flag == Configuration.ORIENTATION_PORTRAIT) {
   display.setText("In PORTRAIT MODE");
  } else if (flag == Configuration.ORIENTATION_LANDSCAPE) {
   display.setText("In LANDSCAPE MODE");
  }

 }

}

Read More »

Android Save And Restore Instance On Configuration Change

A Scenario in which activity will be destroyed and recreated each time when the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity due to the configuration change the data which is available in portrait mode gets lost in landscape and vice-verse , to save this data during configuration change android framework provides two important methods lets see how to use them with example .



XML Layout


file : activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context="com.tutorialsbuzz.saveinstance.MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btnClick"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textSize="30sp"
        android:textStyle="bold" />

</LinearLayout>

onSaveInstanceState() : The system calls this method when the user is leaving your activity , and the data are store into bundle object .

onRestoreInstanceState() : The System calls this method when the activity is recreated by passing the bundle object which was saved during onSaveInstanceState() .

Activity


file : MainActivity.java
package com.tutorialsbuzz.saveinstance;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    EditText editText;
    TextView textView;

    String data = null;

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

        editText = (EditText) findViewById(R.id.editText1);
        textView = (TextView) findViewById(R.id.textView1);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("key", data);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        data = savedInstanceState.getString("key");
        textView.setText(data);
    }

    public void btnClick(View view) {
        data = editText.getText().toString();
        editText.setText("");
        textView.setText(data);
    }

}


when you run the application and set the textview with the string from editext box onclick of button , after that rotate the device in landscape and portrait mode . and you will see the data is saved between configuration change .
Read More »

Android Styling Toolbar


In the previous tutorial we have seen how to add toolbar widget to your activity layout in this tutorial we will see how to style the toolbar widget with background color , height and also styling the title and subtitle text properties of toolbar .



Setting Toolbar Background 


To set the background color for toolbar you need to use colorPrimary item attribute and set the background with color of your choice  .

Toolbar Widget
<android.support.v7.widget.Toolbar
        android:background="?attr/colorPrimary"
        --------------------------------------
        --------------------------------------
        />

Style
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       <item name="colorPrimary">@color/LightBlue</item>
     
    </style>


Setting Toolbar Height


To set the height for toolbar you need to use actionBarSize item attribute and set the height  .

Toolbar Widget
   <android.support.v7.widget.Toolbar
        android:minHeight="?attr/actionBarSize"
        --------------------------------------
        --------------------------------------
        />

Style
 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       <item name="actionBarSize">100dp</item>
     
    </style>


Styling Toolbar Title


To style the toolbar title you need to add  "app:titleTextAppearance='AppTheme.Toolbar.Title' " attribute to Toolbar widget and inside the style.xml file add new style tag whose parent attribute is set with "TextAppearance.Widget.AppCompat.Toolbar.Title" and inside which you can set the text style , size ,color  .

Toolbar Widget
<android.support.v7.widget.Toolbar
        app:titleTextAppearance="@style/AppTheme.Toolbar.Title"
        --------------------------------------
        --------------------------------------
        />

Style
<style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">@color/White</item>
        <item name="android:textStyle">bold</item>
    </style>



Styling Toolbar SubTitle


To style the toolbar subtitle you need to add  "app:titleTextAppearance='AppTheme.Toolbar.SubTitle' " attribute to Toolbar widget and inside the style.xml file add new style tag whose parent attribute is set with "TextAppearance.Widget.AppCompat.SubToolbar.Title" and inside which you can set the text style , size ,color .

Toolbar Widget
<android.support.v7.widget.Toolbar
        app:subtitleTextAppearance="@style/AppTheme.Toolbar.SubTitle"
        --------------------------------------
        --------------------------------------
        />

Style
<style name="AppTheme.Toolbar.SubTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
        <item name="android:textColor">@color/Black</item>
        <item name="android:textStyle">bold</item>
    </style>



Read More »