Wednesday 17 August 2016

TextView



Displays text to the user and optionally allows them to edit it. A TextView is a complete text editor, however the basic class is configured to not allow editing;
It can be either single line or multi-line. EditText also support Cut, Copy, Paste.
Long-Tap : Long tapping on edittext box showing Cut, copy, paste option.
Below exaple showing editText
<TextView
   
android:id="@+id/your_id"
   
android:layout_width="match_parent"
   
android:layout_height="wrap_content"
   
android:hint="@string/your_hint"
   
/>
id : Create id for your edittext like -  android:id="@id/name"

Text
Set the text to textview
Code - android:text="your text here"

Text Size
Specify the size of the size.
Size of text like - 16dp, 20sp, 2em ( 1em= 16dp )
code  - android:textSize="16dp"

AutoResizing Width and Height
From Api level 26.
android:autoSizeTextType="uniform"
android:autoSizeMaxTextSize="24dp"
android:autoSizeMinTextSize="12dp"
android:autoSizeStepGranularity="2dp"

Text Alignment
Set Text Left, Right, Centre and more in EditText
code - android:textAlignment="center"

Text  All Caps
Make all text Capital in Textview
must be a boolean ( true/False )
code -  android:textAllCaps="true"

Text Color
Set the color of the text.
Color should be Hexadecimal (#000000 - #ffffff), octal  [Range 0-255] ( rgb(212,212,212,0.5 )
code - android:textColor="#12E9fa"
 
 
Background
Set the background color as a image, color.
code - android:background="@drawable/abc"

Text Style
Style (bold , italic, bolditalic) for the text.
Must be one or more (separated by '|') of the following constant values.
Value -
Normal             -           0
Bold                 -           1
Italic                 -           2
code - android:textStyle="bold"

Typeface
Typeface (normal, sans, serif, monospace) for the text.
Must be one of the following constant values.
Value -
Normal             -           0
Sans                -           1
Serif                 -           2
Monospace      -           3
code  - android:typeface="monospace"

Text Appearance
Default appearance of text: color, typeface, size, and style.
code - android:textAppearance="@style/TextAppearance.AppCompat.Large"
 
Some Attribute -
textAppearanceLarge :  style for "large" text. Defaults to primary text color.
Text Color Highlight
Color of the text selection highlight.
code - android:textColorHighlight="#12e7ff"

Text Direction
Set the direction of the text
rtl for Right to Left direction.
code - android:textDirection="rtl"
 
Text Single Line
Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines,
Must be boolean ( True / False )
code - android:singleLine="true"

Text Shadow color
Place a blurred shadow of text underneath the text, drawn with the specified color.
Must be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb" or hex (#ffaa77)
code - android:shadowColor="#aa6600"

Text ShadowDX
Horizontal offset of the text shadow.
Must be a floating point value, such as "1.2".
code - android:shadowDx="1.2"
 
Text ShadowDY
Vertical offset of the text shadow.
Must be a floating point value, such as "1.2".
code - android:shadowDy="1.2"
 
Text Shadow Radius
Blur radius of the text shadow.
Must be a floating point value, such as "1.2".
code - android:shadowRadius="1.2"
 
 
 
Text IsSelectable
Indicates that the content of a non-editable text can be selected.
Must be a boolean value, either "true" or "false".
code - android:textIsSelectable="true"

Text  ScaleX
Sets the horizontal scaling factor for the text.
Must be a floating point value, such as "1.2".
Code - android:textScaleX="12"


Visibility
show or hide the edittext
Must be 'Visible', 'Invisivble' or 'Gone'.
code  - android:visibility="invisible"

Letter  Spacing
Specing between character .
Must be a floating point value, such as "1.2".
method - android:letterSpacing="2"  range:"1 to depend on you"
 

Line Spacing
Spacing between two line
 
code - android:lineSpacingExtra="16dp"

Hint
Show hint for type of input
Method - android:hint="search_hint"
 
Hint Color
Set color for hint text
code - android:textColorHint="#ff6600"

Line
Makes the TextView be exactly this many lines tall.
Must be an integer value, such as "3".
Code - android:lines="2"
 
Font Family
Font family (named by string) for the text.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
code - android:fontFamily="cursive"
 

Gravity
Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view.
Attribute are - top, bottom, left, right, centre, start, end
code - android:gravity="center"

Margin
Specifies extra space on the bottom side of this view. This space is outside this view's bounds. Margin values should be positive.
Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).
Code - android:layout_margin="46dp"
 
XML Attributes
Attribute Name
Related Method
Description
Specifies extra space on the bottom side of this view. 
Specifies extra space on the end side of this view. 
Specifies extra space on the left side of this view. 
Specifies extra space on the right side of this view. 
Specifies extra space on the start side of this view. 
Specifies extra space on the top side of this view. 


Padding
Sets the padding, in pixels, of all four edges. Padding is defined as space between the edges of the view and the view's content. A views size will include it's padding. If a background is provided, the padding will initially be set to that (0 if the drawable does not have padding). Explicitly setting a padding value will override the corresponding padding found in the background.
Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).
code - android:padding="16dp"

 
XML Attributes
Attribute Name
Related Method
Description
Sets the padding, in pixels, of the bottom edge; see padding.
Sets the padding, in pixels, of the end edge; see padding.
Sets the padding, in pixels, of the left edge; see padding.
Sets the padding, in pixels, of the right edge; see padding.
Sets the padding, in pixels, of the start edge; see padding.
Sets the padding, in pixels, of the top edge; see padding.


onClick
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v)method of your context (typically, your Activity).
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
code - android:onClick="method name"

rotation
rotation of the view, in degrees.
Must be a floating point value, such as "1.2".
code  - android:rotation="12"

Attribute                   -                       Description
android:rotationX           -              rotation of the view around the x axis, in degrees.
android:rotationY           -              rotation of the view around the y axis, in degrees.

Save Enabled
If false, no state will be saved for this view when it is being frozen. The default is true, allowing the view to be saved (however it also must have an ID assigned to it for its state to be saved). Setting this to false only disables the state for this view, not for its children which may still be saved.
Must be a boolean value, either "true" or "false".
code - android:saveEnabled="false"

Sound Effect  Enabled
Boolean that controls whether a view should have sound effects enabled for events such as clicking and touching.
Must be a boolean value, either "true" or "false".
code - android:soundEffectsEnabled="true"
 
 
Tag
Supply a tag for this view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag(). It is generally preferable to use IDs (through the android:id attribute) instead of tags because they are faster and allow for compile-time type checking.
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
code  -  android:tag="tag name here"

ForeGround
Defines the drawable to draw over the content. This can be used as an overlay. The foreground drawable participates in the padding of the content if the gravity is set to fill.
May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb" or image
code - android:foreground="@drawable/abc"

foreGround Gravity
Defines the gravity to apply to the foreground drawable. The gravity defaults to fill.
Must be one or more (separated by '|') of the following constant values.
Constant
Value
Description
top
0x30
Push object to the top of its container, not changing its size.
bottom
0x50
Push object to the bottom of its container, not changing its size.
left
0x03
Push object to the left of its container, not changing its size.
right
0x05
Push object to the right of its container, not changing its size.
center_vertical
0x10
Place object in the vertical center of its container, not changing its size.
fill_vertical
0x70
Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal
0x01
Place object in the horizontal center of its container, not changing its size.
fill_horizontal
0x07
Grow the horizontal size of the object if needed so it completely fills its container.
center
0x11
Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill
0x77
Grow the horizontal and vertical size of the object if needed so it completely fills its container.
clip_vertical
0x80
Additional option that can be set to have the top and/or bottom edges of the child clipped to its container's bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges.
clip_horizontal
0x08
Additional option that can be set to have the left and/or right edges of the child clipped to its container's bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges.


foregroundTint
Tint to apply to the foreground. if your foreground is image then overwrite with tint color.
Must be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
android:foregroundTint="#12e7ff"


 foregroundTintMode
Blending mode used to apply the foreground tint. awsm
Must be one of the following constant values.
Constant
Value
Description
src_over
3
The tint is drawn on top of the drawable. [Sa + (1 - Sa)*Da, Rc = Sc + (1 - Sa)*Dc]
src_in
5
The tint is masked by the alpha channel of the drawable. The drawable’s color channels are thrown out. [Sa * Da, Sc * Da]
src_atop
9
The tint is drawn above the drawable, but with the drawable’s alpha channel masking the result. [Da, Sc * Da + (1 - Sa) * Dc]
multiply
14
Multiplies the color and alpha channels of the drawable with those of the tint. [Sa * Da, Sc * Dc]
screen
15
[Sa + Da - Sa * Da, Sc + Dc - Sc * Dc]
add
16
Combines the tint and drawable color and alpha channels, clamping the result to valid color values. Saturate(S + D)

code -  android:foregroundTintMode="add"



inputType
The type of data being placed in a text field, used to help an input method decide how to let the user enter text. The constants here correspond to those defined by InputType. Generally you can select a single value, though some can be combined together as indicated. Setting this attribute to anything besides none also implies that the text is editable.
Must be one or more (separated by '|') of the following constant values.
Constant
Value
Description
none
0x00000000
There is no content type. The text is not editable.
text
0x00000001
Just plain old text. Corresponds to 
textCapCharacters
0x00001001
Can be combined with text and its variations to request capitalization of
 all characters. Corresponds to TYPE_TEXT_FLAG_CAP_CHARACTERS.
textCapWords
0x00002001
Can be combined with text and its variations to request capitalization
of the first character of every word. Corresponds to 
textCapSentences
0x00004001
Can be combined with text and its variations to request capitalization of
 the first character of every sentence. Corresponds to 
textAutoCorrect
0x00008001
Can be combined with text and its variations to request auto-correction
of text being input. Corresponds to TYPE_TEXT_FLAG_AUTO_CORRECT.
textAutoComplete
0x00010001
Can be combined with text and its variations to specify that this field will
be doing its own auto-completion and talking with the input method
appropriately. Corresponds toTYPE_TEXT_FLAG_AUTO_COMPLETE.
textMultiLine
0x00020001
Can be combined with text and its variations to allow multiple lines of text in the field. If this flag is not set, the text field will be constrained to a single line. Corresponds toTYPE_TEXT_FLAG_MULTI_LINE.
textImeMultiLine
0x00040001
Can be combined with text and its variations to indicate that though the
 regular text view should not be multiple lines, the IME should provide
 multiple lines if it can. Corresponds toTYPE_TEXT_FLAG_IME_MULTI_LINE.
textNoSuggestions
0x00080001
Can be combined with text and its variations to indicate that the IME
should not show any dictionary-based word suggestions. Corresponds to TYPE_TEXT_FLAG_NO_SUGGESTIONS.
textUri
0x00000011
Text that will be used as a URI. Corresponds to 
textEmailAddress
0x00000021
Text that will be used as an e-mail address. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_EMAIL_ADDRESS.
textEmailSubject
0x00000031
Text that is being supplied as the subject of an e-mail. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_EMAIL_SUBJECT.
textShortMessage
0x00000041
Text that is the content of a short message. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_SHORT_MESSAGE.
textLongMessage
0x00000051
Text that is the content of a long message. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_LONG_MESSAGE.
textPersonName
0x00000061
Text that is the name of a person. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_PERSON_NAME.
textPostalAddress
0x00000071
Text that is being supplied as a postal mailing address. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_POSTAL_ADDRESS.
textPassword
0x00000081
Text that is a password. Corresponds to 
textVisiblePassword
0x00000091
Text that is a password that should be visible. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_VISIBLE_PASSWORD.
textWebEditText
0x000000a1
Text that is being supplied as text in a web form. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_WEB_EDIT_TEXT.
textFilter
0x000000b1
Text that is filtering some other data. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_FILTER.
textPhonetic
0x000000c1
Text that is for phonetic pronunciation, such as a phonetic name field in a contact entry. Corresponds to TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PHONETIC.
textWebEmailAddress
0x000000d1
Text that will be used as an e-mail address on a web form. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS.
textWebPassword
0x000000e1
Text that will be used as a password on a web form. Corresponds to TYPE_CLASS_TEXT |TYPE_TEXT_VARIATION_WEB_PASSWORD.
number
0x00000002
A numeric only field. Corresponds to 
numberSigned
0x00001002
Can be combined with number and its other options to allow a signed
number. Corresponds to
numberDecimal
0x00002002
Can be combined with number and its other options to allow a decimal
(fractional) number. Corresponds to 
numberPassword
0x00000012
A numeric password field. Corresponds to TYPE_CLASS_NUMBER |TYPE_NUMBER_VARIATION_PASSWORD.
phone
0x00000003
For entering a phone number. Corresponds to TYPE_CLASS_PHONE.
datetime
0x00000004
For entering a date and time. Corresponds to TYPE_CLASS_DATETIME |TYPE_DATETIME_VARIATION_NORMAL.
date
0x00000014
For entering a date. Corresponds to
time
0x00000024
For entering a time. Corresponds to 

//-------------------------------   Scroll bar start here

ScrollIndicators
Defines which scroll indicators should be displayed when the view can be scrolled. Multiple values may be combined using logical OR, for example "top|bottom".
Must be one or more (separated by '|') of the following constant values.
Constant
Value
Description
none
0x00
No scroll indicators are displayed.
top
0x01
Displays top scroll indicator when view can be scrolled up.
bottom
0x02
Displays bottom scroll indicator when vew can be scrolled down.
left
0x04
Displays left scroll indicator when vew can be scrolled left.
right
0x08
Displays right scroll indicator when vew can be scrolled right.
start
0x10
Displays right scroll indicator when vew can be scrolled in the start direction.
end
0x20
Displays right scroll indicator when vew can be scrolled in the end direction.

code - android:scrollIndicators="bottom"

ScrollX
The initial horizontal scroll offset, in pixels.
Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).
code - android:scrollX="14sp"

ScrollY
The initial vertical scroll offset, in pixels.
Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).
code -  android:scrollY="14sp"

 scrollbarAlwaysDrawHorizontalTrack
Defines whether the horizontal scrollbar track should always be drawn.
Must be a boolean value, either "true" or "false".
android:scrollbarAlwaysDrawHorizontalTrack="true"
 
Below code for vertical

  android:scrollbarAlwaysDrawVerticalTrack="true"

scrollbarDefaultDelayBeforeFade
Defines the delay in milliseconds that a scrollbar waits before fade out.
Must be an integer value, such as "100".
code - android:scrollbarDefaultDelayBeforeFade="100"

scrollbarFadeDuration
Defines the delay in milliseconds that a scrollbar takes to fade out.
Must be an integer value, such as "100".
code - android:scrollbarFadeDuration="100"

scrollbarSize
Sets the width of vertical scrollbars and height of horizontal scrollbars.
Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).
code  - android:scrollbarSize="100dp"

scrollbarStyle
Controls the scrollbar style and position. The scrollbars can be overlaid or inset. When inset, they add to the padding of the view. And the scrollbars can be drawn inside the padding area or on the edge of the view. For example, if a view has a background drawable and you want to draw the scrollbars inside the padding specified by the drawable, you can use insideOverlay or insideInset. If you want them to appear at the edge of the view, ignoring the padding, then you can use outsideOverlay or outsideInset.
Must be one of the following constant values.
Constant
Value
Description
insideOverlay
0x0
Inside the padding and overlaid
insideInset
0x01000000
Inside the padding and inset
outsideOverlay
0x02000000
Edge of the view and overlaid
outsideInset
0x03000000
Edge of the view and inset


scrollbarThumbHorizontal
Defines the horizontal scrollbar thumb drawable.
android:scrollbarThumbHorizontal="@drawable/abc"

scrollbarThumbVertical
Defines the vertical scrollbar thumb drawable.
android:scrollbarThumbVertical="@drawable/abc"
 
 scrollbarTrackHorizontal
Defines the horizontal scrollbar track drawable.
code - android:scrollbarTrackHorizontal="@drawable/abc"
 
 
 
scrollbarTrackVertical
 
Defines the vertical scrollbar track drawable.
code - android:scrollbarTrackVertical="@drawable/abc"
 
 
 
scrollbars
Defines which scrollbars should be displayed on scrolling or not.
Must be one or more (separated by '|') of the following constant values.
Constant
Value
Description
none
0x00000000
No scrollbar is displayed.
horizontal
0x00000100
Displays horizontal scrollbar only.
vertical
0x00000200
Displays vertical scrollbar only.

code - android:scrollbars="horizontal"

--------------------------------------
Java Code

XML PART
 
<TextView

    android:id="@+id/textview"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:hint="editText Demo"

    />
 
JAVA PART
public class MainActivity extends AppCompatActivity {



    TextView textView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView =( TextView) findViewById(R.id.textView);  // edittext initialization

        

    }

}

getText()
Obtain text from textView and store it.
Runtime
String string = textView.getText().toString();

setText()
Set  text to edittext .
Runtime
 
 
textView.setText(" Set this value to textView ");
 
Directly, parse value to editText
 
or 
 
String string = " Set this value to textView ";
textView.getText(string);

Store the value to a string first and then set to textView.

selectAll
select all text  of view
Place this code inside button.
code - textView.selectAll();


addTextChangeListner
It perform when change occur in edittext.
code - textView.addTextChangedListener(textWatcher);
this code listen any change in editText then TextWatcher perform task.
Final code -
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"

    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"

    android:orientation="vertical"

    tools:context="sichlearning.example.com.testone.MainActivity">



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello World!"

        android:id="@+id/hello"

        />

    <EditText

        android:id="@+id/edittext"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="editText Demo"

        android:textColor="#ffffff"

        />



    <Button

        android:layout_width="200dp"

        android:layout_height="wrap_content"

        android:text="select all"

        android:onClick="select"

        />

</LinearLayout>

MainActivity.java
package sichlearning.example.com.testone;



import android.graphics.Color;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.support.v7.app.AppCompatDelegate;

import android.text.Editable;

import android.text.TextWatcher;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;



public class MainActivity extends AppCompatActivity {



    EditText editText;

    TextView textView;

    TextWatcher textWatcher;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        editText=(EditText) findViewById(R.id.edittext);

        textView=(TextView)findViewById(R.id.hello);







        textWatcher=new TextWatcher() {

            @Override

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                editText.setBackgroundColor(Color.DKGRAY);

        }



            @Override

            public void onTextChanged(CharSequence s, int start, int before, int count) {

                editText.setBackgroundColor(Color.parseColor("#12e7ff"));

            }



            @Override

            public void afterTextChanged(Editable s) {

             //   editText.setBackgroundColor(0xff0000ff);

                editText.setBackgroundColor(Color.RED);

            }

        };

        editText.addTextChangedListener(textWatcher);

    }



    public void select(View view)

    {



    }

}


setBackGroundColor
Change the color of edittext.
code -                editText.setBackgroundColor(Color.DKGRAY);
                          editText.setBackgroundColor(Color.parseColor("#12e7ff"));

append
Add text or string to view or any character sequence.
Code - editText.append( string );
 example - editText.append("hello");
 
or
String hello="hello diva";
 
editText.append(hello);

 append (CharSequence text, int start, int end)
add text in view with specified range ( start and end range )
code - editText.append(Char squence, int start,int end);
like - editText.append("hellodivakar",3,5);
this code only 'lo' to string

STYLING
add style
To add style to edittext, use
<EditText  
    style="@style/FullWidthEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Subject"/>
style in style.xml
We need to specify name of the style because we access style with name in editText.
<style name="FullWidthEditText" parent="Widget.AppCompat.EditText">  
    <item name="android:padding">20dp</item>
    <item name="android:background">@null</item>
    <item name="android:textSize">@dimen/abc_text_size_subhead_material</item>
</style>  
add style-shape
Add shape to editext.
Step 1. create a xml file (radiant_bachground.xml ) to drawable folder and place this code

radial_background.xml
<?xml version="1.0" encoding="UTF-8"?>
    <gradient
            android:type="radial"
            android:startColor="#343030"
            android:endColor="#151515"
            android:gradientRadius="300"
            android:angle="270"
            android:centerY="0.3"/>
</shape>

step -2.  Add this code to your view ( edittext, textview, button or more ) to change background
android:background="@drawable/radial_background"

Text counter
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<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="sichlearning.example.com.textcounter.MainActivity">



    <EditText

        android:id="@+id/editText1"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:background="#fff"

        android:layout_marginBottom="50dp"

        android:padding="30dp"

        android:layout_alignParentLeft="true"

        android:layout_alignParentTop="true"

        android:maxLength="150"

        android:gravity="top|left"

        android:lineSpacingMultiplier="1.8"

        android:inputType="textMultiLine|textCapSentences" />

    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginLeft="100dp"

        />



</RelativeLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity {



    private TextView textView1;

    private EditText editText1;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        editText1=(EditText)findViewById(R.id.editText1);

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



        TextWatcher textWatcher=new TextWatcher() {

            @Override

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {



            }



            @Override

            public void onTextChanged(CharSequence s, int start, int before, int count) {



            }



            @Override

            public void afterTextChanged(Editable s) {

                textView1.setText(150 - s.toString().length() + "/150");

            }

        };

        editText1.addTextChangedListener(textWatcher);

    }}


Dynamic View
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"

    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"

    android:orientation="vertical"

    tools:context=".MainActivity" >



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="hello_world" />

    <RelativeLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content">

        <Button

            android:id="@+id/add"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_alignParentRight="true"

            android:text="Add"/>

        <EditText

            android:id="@+id/textin"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:layout_alignParentLeft="true"

            android:layout_toLeftOf="@id/add"/>

    </RelativeLayout>

    <LinearLayout

        android:id="@+id/container"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="vertical">

    </LinearLayout>



</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {



    EditText textIn;

    Button buttonAdd;

    LinearLayout container;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        textIn = (EditText)findViewById(R.id.textin);

        buttonAdd = (Button)findViewById(R.id.add);

        container = (LinearLayout)findViewById(R.id.container);



        buttonAdd.setOnClickListener(new View.OnClickListener(){



            @Override

            public void onClick(View arg0) {

                LayoutInflater layoutInflater =

                        (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                final View addView = layoutInflater.inflate(R.layout.row, null);

                TextView textOut = (TextView)addView.findViewById(R.id.textout);

                textOut.setText(textIn.getText().toString());

                Button buttonRemove = (Button)addView.findViewById(R.id.remove);

                buttonRemove.setOnClickListener(new View.OnClickListener(){



                    @Override

                    public void onClick(View v) {

                        ((LinearLayout)addView.getParent()).removeView(addView);

                    }});



                container.addView(addView);

            }});



    }



}

row.xml
<?xml version="1.0" encoding="utf-8"?>

<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="wrap_content">

    <Button

        android:id="@+id/remove"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:text="Remove"/>

    <TextView

        android:id="@+id/textout"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_toLeftOf="@id/remove"/>

</RelativeLayout>





No comments:

Post a Comment