Android Common Views

Defining Views and their Attributes

Defining view components within a layout is a critical part of Android development. Let’s take a look at common views as well as common attributes of views.

Common Views

The six most common views are:

  • TextView displays a formatted text label
  • ImageView displays an image resource
  • Button can be clicked to perform an action
  • ImageButton displays a clickable image
  • EditText is an editable text field for user input
  • ListView is a scrollable list of items containing other views

View Identifiers

Any view can have an identifier attached that uniquely names that view for later access. You can assign a view an id within the XML layout:

<Button android:id="@+id/my_button" />

This id can then be accessed within the Java code for the corresponding activity (in onCreate of Activity for example):

Button myButton = (Button) findViewById(R.id.my_button);

Another important note is that any view with an id specified will automatically retain its state on a configuration change (i.e phone orientation switch).

View Height and Width

Every view has height and width properties controlling the size of the view. Height and width have to be defined in the XML for every view with:

<TextView
  android:layout_width="165dp" 
  android:layout_height="wrap_content" />

This can take the form of wrap_content (adjust height and width to the content size), match_parent (adjust height and width to the full size of the parent container), and a dimensions value such as 120dp. This can be changed at runtime in a number of ways:

// Change the width or height
int newInPixels = 50;
view.setLayoutParams(new LayoutParams(newInPixels, newInPixels));
// Trigger invalidation of the view to force adjustment
view.requestLayout();

Or we can change just the width or height individually:

int newDimensionInPixels = 50;
view.getLayoutParams().width = newDimensionInPixels;
view.getLayoutParams().height = newDimensionInPixels;
// Trigger invalidation of the view to force adjustment
view.requestLayout();

We can also set these dimensions in dp rather than pixels with:

int newDimensionInPixels = 50;
// convert to 50dp
int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, newDimensionInPixels, 
    getResources().getDisplayMetrics());
view.getLayoutParams().width = newDimensionInPixels;
view.getLayoutParams().height = dimensionInDp;
// Trigger invalidation of the view to force adjustment
view.requestLayout();

Views Margin and Padding

Margins and padding values for views allows us to position and space elements in a layout.

  • Layout Margin defines the amount of space around the outside of a view
  • Padding defines the amount of space around the contents or children of a view.

An example of setting margins and padding:

<LinearLayout>
   <TextView android:layout_margin="5dp" android:padding="5dp">
   <Button layout_marginBottom="5dp">
</LinearLayout>

View Gravity

Gravity can be used to define the direction of the contents of a view.

  • gravity determines the direction that the contents of a view will align (like CSS text-align).
  • layout_gravity determines the direction of the view within it’s parent (like CSS float).

An example of applying gravity:

<TextView
  android:gravity="left"
  android:layout_gravity="right"
  android:layout_width="165dp" android:layout_height="wrap_content"
  android:textSize="12sp" android:text="@string/hello_world" />

View Attributes

Every view has many different attributes which can be applied to manage various properties.

  • Certain properties are shared across many views such as android:layout_width
  • Other properties are based on a view’s function such as android:textColor

Common view attributes include:

Attribute Description Example Value
android:background Background for the view #ffffff
android:onClick Method to invoke when clicked onButtonClicked
android:visibility Controls how view appears invisible
android:hint Hint text to display when empty @string/hint
android:text Text to display in view @string/foo
android:textColor Color of the text #000000
android:textSize Size of the text 21sp
android:textStyle Style of the text formatting bold

Review the View docs and TextView docs for a list of additional attributes. An example of setting view attributes:

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/hello_world"
   android:background="#000"
   android:textColor="#fff"
   android:layout_centerHorizontal="true"
/>

TextView

Every Android device comes with a collection of standard fonts: Droid Sans, Droid Sans Mono and Droid Serif. They were designed to be optimal for mobile displays, so these are the three fonts you will be working with most of the time and they can be styled using a handful of XML attributes. You might, however, see the need to use custom fonts for special purposes.

This guide will take a look at the TextView and discuss common properties associated with this view as well as how to setup custom typefaces.

Text Attributes

Typeface

As stated in the overview, there are three different default typefaces which are known as the Droid family of fonts: sans, monospace and serif. You can specify any one of them as the value for the android:typeface attribute in the XML:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="This is a 'sans' demo!"
    android:typeface="sans"
/>

Here’s how they look:

fonts

In addition to the above, there is another attribute value named “normal” which defaults to the sans typeface.

Text Style

The android:textStyle attribute can be used to put emphasis on the text. The possible values are: normal, bold, italic. You can also specify bold|italic.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="This is bold!"
    android:textStyle="bold"
/>

A sampling of styles can be seen below:

style

Text Size

android:textSize specifies the font size. Its value must consist of two parts: a floating-point number followed by a unit. It is generally a good practice to use the sp unit so the size can scale depending on user settings.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="14sp is the 'normal' size."
    android:textSize="14sp"
/>

A sampling of styles can be seen below:

style

Too many type sizes and styles at once can wreck any layout. The basic set of styles are based on a typographic scale of 12, 14, 16, 20, and 34. Refer to this typography styles guide for more details.

Text Truncation

There are a few ways to truncate text within a TextView. First, to restrict the total number of lines of text we can use android:maxLines and android:minLines:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minLines="1"
    android:maxLines="2"
/>

In addition, we can use android:ellipsize to begin truncating text

<TextView
    ...
    android:ellipsize="end"
    android:singleLine="true"
/>

Following values are available for ellipsize: start for ...bccc, end for aaab..., middle for aa...cc, and marquee for aaabbbccc sliding from left to right. Example:

style

There is a known issue with ellipsize and multi-line text, see this MultiplelineEllipsizeTextView library for an alternative.

Text Color

The android:textColor and android:textColorLink attribute values are hexadecimal RGB values with an optional alpha channel, similar to what’s found in CSS:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="A light blue color."
    android:textColor="#00ccff"
    android:textColorLink="#8DE67F"
/>

The android:textColorLink attribute controls the highlighting for [[hyperlinks embedded within the TextView|Working-with-the-TextView#inserting-html-formatting]]. This results in:

We can edit the color at runtime with:

// Based on hex value
textView.setColor(Color.setTextColor(Color.parseColor("#000000"));
// based on a color resource file
textView.setTextColor(ContextCompat.getColor(context, R.color.your_color));
// based on preset colors
textView.setColor(Color.setTextColor(Color.RED));

Text Shadow

You can use three different attributes to customize the appearance of your text shadow:

  • android:shadowColor - Shadow color in the same format as textColor.
  • android:shadowRadius - Radius of the shadow specified as a floating point number.
  • android:shadowDx - The shadow’s horizontal offset specified as a floating point number.
  • android:shadowDy - The shadow’s vertical offset specified as a floating point number.

The floating point numbers don’t have a specific unit - they are merely arbitrary factors.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="A light blue shadow."
    android:shadowColor="#00ccff"
    android:shadowRadius="2"
    android:shadowDx="1"
    android:shadowDy="1"
/>

This results in:

Various Text Properties

There are many other text properties including android:lineSpacingMultiplier, android:letterSpacing, android:textAllCaps, android:includeFontPadding and many others:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:lineSpacingMultiplier="1.1"
    android:textAllCaps="true"
/>

android:includeFontPadding removes the extra padding around large fonts. android:lineSpacingMultiplier governs the spacing between lines with a default of “1”.

Inserting HTML Formatting

TextView natively supports HTML by translating HTML tags to spannable sections within the view. To apply basic HTML formatting to text, add text to the TextView with:

TextView view = (TextView)findViewById(R.id.sampleText);
String formattedText = "This <i>is</i> a <b>test</b> of <a href='http://foo.com'>html</a>";
// or getString(R.string.htmlFormattedText);
view.setText(Html.fromHtml(formattedText));

This results in:

Note that all tags are not supported. See this article for a more detailed look at supported tags and usages.

Android N Usage

As of Android N, the signature for the method changed, requiring there to be a check depending on version to remove the deprecation warning:

@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
    Spanned result;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
       result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
    } else {
       result = Html.fromHtml(html);
    }
    return result;
}

You can read more about the html modes here.

Setting Font Colors

For setting font colors, we can use the <font> tag as shown:

Html.fromHtml("Nice! <font color='#c5c5c5'>This text has a color</font>. This doesn't"); 

And you should be all set.

Storing Long HTML Strings

If you want to store your HTML text within res/values/strings.xml, you have to use CDATA to escape such as:

<?xml version="1.0" encoding="utf-8"?>
<string name="htmlFormattedText">
    <![CDATA[
        Please <a href="http://highlight.com">let us know</a> if you have <b>feedback on this</b> or if 
        you would like to log in with <i>another identity service</i>. Thanks!   
    ]]>
</string>

and access the content with getString(R.string.htmlFormattedText) to load this within the TextView.

For more advanced cases, you can also check out the html-textview library which adds support for almost any HTML tag within this third-party TextView.

Autolinking URLs

TextView has native support for automatically locating URLs within the their text content and making them clickable links which can be opened in the browser. To do this, enable the android:autolink property:

<TextView
     android:id="@+id/custom_font"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:autoLink="all"
     android:linksClickable="true"
/>

This results in:

Issues with ListView

One known issue when using android:autoLink or the Linkify class is that it may break the ability to respond to events on the ListView through setOnItemClickListener. Check out this solution which extends TextView in order to modify the onTouchEvent to correctly propagate the click. You basically need to create a LinkifiedTextView and use this special View in place of any of your TextView’s that need auto-link detection.

In addition, review this stackoverflow post or this android issue for additional context.

Displaying Images within a TextView

A TextView is actually surprisingly powerful and actually supports having images displayed as a part of it’s content area. Any images stored in the “drawable” folders can actually be embedded within a TextView at several key locations in relation to the text using the android:drawableRight and the android:drawablePadding property. For example:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"     
    android:gravity="center"
    android:text="@string/my_contacts"
    android:drawableRight="@drawable/ic_action_add_group"
    android:drawablePadding="8dp"
/>

Which results in:

Contacts View

In Android, many views inherit from TextView such as Buttons, EditTexts, RadioButtons which means that all of these views support the same functionality. For example, we can also do:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/user_name"
    android:drawableLeft="@drawable/ic_action_person"
    android:drawablePadding="8dp"
/>

Which results in:

EditText with drawable

The relevant attributes here are drawableLeft, drawableRight, drawableTop and drawableBottom along with drawablePadding. Check out this TextView article for a more detailed look at how to use this functionality.

Note that if you want to be able to better control the size or scale of the drawables, check out this handy TextView extension or this bitmap drawable approach. You can also make calls to setCompoundDrawablesWithIntrinsicBounds on the TextView.

Using Custom Fonts

We can actually use any custom font that we’d like within our applications. Check out fontsquirrel for an easy source of free fonts. For example, we can download Chantelli Antiqua as an example.

Fonts are stored in the “assets” folder. In Android Studio, File > New > folder > Assets Folder. Now download any font and place the TTF file in the assets/fonts directory:

We’re going to use a basic layout file with a TextView, marked with an id of “custom_font” so we can access it in our code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
 
    <TextView
            android:id="@+id/custom_font"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="This is the Chantelli Antiqua font."
    />
</LinearLayout>

To set the custom font manually, open your activity file and insert this into the onCreate() method:

// Get access to our TextView
TextView txt = (TextView) findViewById(R.id.custom_font);
// Create the TypeFace from the TTF asset
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Chantelli_Antiqua.ttf");
// Assign the typeface to the view
txt.setTypeface(font);

Alternatively, you can use the third-party calligraphy library:

<TextView fontPath="fonts/Chantelli_Antiqua.ttf"/>

Either method will will result in:

custom

You’ll also want to keep an eye on the total size of your custom fonts, as this can grow quite large if you’re using a lot of different typefaces.

Using Spans to Style Sections of Text

Spans come in really handy when we want to apply styles to portions of text within the same TextView. We can change the text color, change the typeface, add an underline, etc, and apply these to only certain portions of the text. The full list of spans shows all the available options.

As an example, let’s say we have a single TextView where we want the first word to show up in red and the second word to have a strikethrough:

Custom

We can accomplish this with spans using the code below:

String firstWord = "Hello";
String secondWord = "World!";

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

// Create a span that will make the text red
ForegroundColorSpan redForegroundColorSpan = new ForegroundColorSpan(
        getResources().getColor(android.R.color.holo_red_dark));

// Use a SpannableStringBuilder so that both the text and the spans are mutable
SpannableStringBuilder ssb = new SpannableStringBuilder(firstWord);

// Apply the color span
ssb.setSpan(
        redForegroundColorSpan,            // the span to add
        0,                                 // the start of the span (inclusive)
        ssb.length(),                      // the end of the span (exclusive)
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // behavior when text is later inserted into the SpannableStringBuilder
                                           // SPAN_EXCLUSIVE_EXCLUSIVE means to not extend the span when additional
                                           // text is added in later

// Add a blank space
ssb.append(" ");

// Create a span that will strikethrough the text
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();

// Add the secondWord and apply the strikethrough span to only the second word
ssb.append(secondWord);
ssb.setSpan(
        strikethroughSpan,
        ssb.length() - secondWord.length(),
        ssb.length(),
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Set the TextView text and denote that it is Editable
// since it's a SpannableStringBuilder
tvHelloWorld.setText(ssb, TextView.BufferType.EDITABLE);

Note: There are 3 different classes that can be used to represent text that has markup attached. SpannableStringBuilder (used above) is the one to use when dealing with mutable spans and mutable text. SpannableString is for mutable spans, but immutable text. And SpannedString is for immutable spans and immutable text.

Creating Clickable Styled Spans

In certain cases, we might want different substrings in a TextView to different styles and then clickable to trigger an action. For example, rendering tweet items where @foo can be clicked in a message to view a user’s profile. For this, you should copy over the PatternEditableBuilder.java utility into your app. You can then use this utility to make clickable spans. For example:

// Set text within a `TextView`
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hey @sarah, where did @jim go? #lost");
// Style clickable spans based on pattern
new PatternEditableBuilder().
    addPattern(Pattern.compile("\\@(\\w+)"), Color.BLUE,
       new PatternEditableBuilder.SpannableClickedListener() {
            @Override
            public void onSpanClicked(String text) {
                Toast.makeText(MainActivity.this, "Clicked username: " + text,
                    Toast.LENGTH_SHORT).show();
            }
       }).into(textView);

and this results in the following:

For more details, view the README for more usage examples.

Button

There are three standard types of buttons:

  • Floating action button: A circular material button that lifts and displays an ink reaction on press.
  • Raised button: A typically rectangular material button that lifts and displays ink reactions on press.
  • Flat button: A button made of ink that displays ink reactions on press but does not lift.

Button Types

To create a button with text, use the following XML :

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="LOGIN" />

If we want the button’s width to be the same as its parent, we would change the android:layout_height to match_parent.

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="LOGIN" />

In Android Studio, we can preview the effect of the wrap_content property on the width of the button.

View Properties

Drawables on buttons

A normal button can also have an image on the left or right, by using the android:drawableLeft and android:drawableRight attributes. Thses drawables have limited use as the images inside them can not be resized.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_text"
    android:drawableLeft="@drawable/button_icon"/>

Floating Action Button

The floating action action button is available as a support package. You need to the Android Support Design v7 package from from Nuget before you can use it in the project.

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    app:srcCompat="@android:drawable/ic_input_add" />

The floating action button is mostly used inside the CoordinatorLayout or FrameLayout. This layout is also included as part of the Android Support Design Package.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>

FAB Properties

Property Description
Position You can position the floating button by using layout_gravity attribute.
Size FAB supports two sizes normal and mini. You can define the size of the button by using app:fabSize attribute
Background Color By default, fab takes colorAccent as background color. If you want to change the background of fab, use app:backgroundTint attribute to define your own background color
Ripple Color Sets the color of the ripple effect of your FloatingActionButton. Can be a color resource or hex string. app:rippleColor
Compat Padding Enable compat padding. Maybe a boolean value, such as true or false. app:useCompatPadding
Elevation Can be a string, integer, boolean, color value, floating point, dimension value. app:elevation

Responding to Click Events

When the user clicks a button, the Button object receives an on-click event.

To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

For example, here’s a layout with a button using android:onClick:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />

Within the Activity that hosts this layout, the following method handles the click event:

/** Called when the user touches the button */
public void sendMessage(View view) {
    // Do something in response to button click
}

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:

  • Be public
  • Return void
  • Define a View as its only parameter (this will be the View that was clicked)

Using an OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout. This might be necessary if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.

To declare the event handler programmatically, create an View.OnClickListener object and assign it to the button by calling setOnClickListener(View.OnClickListener). For example:

Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Do something in response to button click
    }
});

Styling Your Button

The appearance of your button (background image and font) may vary from one device to another, because devices by different manufacturers often have different default styles for input controls.

You can control exactly how your controls are styled using a theme that you apply to your entire application. For instance, to ensure that all devices running Android 4.0 and higher use the Holo theme in your app, declare android:theme="@android:style/Theme.Holo" in your manifest’s <application> element.

To customize individual buttons with a different background, specify the android:background attribute with a drawable or color resource. Alternatively, you can apply a style for the button, which works in a manner similar to HTML styles to define multiple style properties such as the background, font, size, and others.

Borderless Button

A style is used to get the a borderless button. Note that the style does not use the android prefix.

<Button
    style="@style/Widget.AppCompat.Button.Borderless"
    android:text="Borderless Button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

You can also get a coloured borderless button. The default color used is the accent color from the theme.

<Button
    style="@style/Widget.AppCompat.Button.Borderless.Colored"
    android:text="Borderless Button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Custom background

If you want to truly redefine the appearance of your button, you can specify a custom background. Instead of supplying a simple bitmap or color, however, your background should be a state list resource that changes appearance depending on the button’s current state.

You can define the state list in an XML file that defines three different images or colors to use for the different button states.

To create a state list drawable for your button background:

Create three bitmaps for the button background that represent the default, pressed, and focused button states. To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps. Place the bitmaps into the res/drawable/ directory of your project. Be sure each bitmap is named properly to reflect the button state that they each represent, such as button_default.9.png, button_pressed.9.png, and button_focused.9.png. Create a new XML file in the res/drawable/ directory (name it something like button_custom.xml). Insert the following XML:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_default" />
</selector>

This defines a single drawable resource, which will change its image based on the current state of the button.

  • The first <item> defines the bitmap to use when the button is pressed (activated).
  • The second <item> defines the bitmap to use when the button is focused (when the button is highlighted using the trackball or directional pad).
  • The third <item> defines the bitmap to use when the button is in the default state (it’s neither pressed nor focused).

Note: The order of the <item> elements is important. When this drawable is referenced, the <item> elements are traversed in-order to determine which one is appropriate for the current button state. Because the default bitmap is last, it is only applied when the conditions android:state_pressed and android:state_focused have both evaluated as false.

This XML file now represents a single drawable resource and when referenced by a Button for its background, the image displayed will change based on these three states. Then simply apply the drawable XML file as the button background:

<Button
    android:id="@+id/button_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage"
    android:background="@drawable/button_custom"  />

EditText

The EditText is the standard text entry widget in Android apps. If the user needs to enter text into an app, this is the primary way for them to do that.

EditText

There are many important properties that can be set to customize the behavior of an EditText. Several of these are listed below. Check out the official text fields guide for even more input field details.

Usage

An EditText is added to a layout with all default behaviors with the following XML:

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

Note that an EditText is simply a thin extension of the [[TextView|Working-with-the-TextView]] and inherits all of the same properties.

Retrieving the Value

Getting the value of the text entered into an EditText is as follows:

EditText simpleEditText = (EditText) findViewById(R.id.et_simple);
String strValue = simpleEditText.getText().toString();

Customizing the Input Type

By default, any text contents within an EditText control is displayed as plain text. By setting inputType, we can facilitate input of different types of information, like phone numbers and passwords:

<EditText
    ...
    android:inputType="phone">
</EditText>

Most common input types include:

Type Description
textUri Text that will be used as a URI
textEmailAddress Text that will be used as an e-mail address
textPersonName Text that is the name of a person
textPassword Text that is a password that should be obscured
textVisiblePassword Text, next button, and no microphone input
number A numeric only field
phone For entering a phone number
date For entering a date
time For entering a time
textMultiLine Allow multiple lines of text in the field

You can set multiple inputType attributes if needed (separated by ‘|’)

<EditText
  android:inputType="textCapSentences|textMultiline"
/>

You can see a list of all available input types here.

Further Entry Customization

We might want to limit the entry to a single-line of text (avoid newlines):

<EditText
  android:maxLines="1"
  android:lines="1"
/>

You can limit the characters that can be entered into a field using the digits attribute:

<EditText
  android:inputType="number"
  android:digits="01"
/>

This would restrict the digits entered to just “0” and “1”. We might want to limit the total number of characters with:

<EditText
  android:maxLength="5"
/>

Using these properties we can define the expected input behavior for text fields.

Adjusting Colors

You can adjust the highlight background color of selected text within an EditText with the android:textColorHighlight property:

<EditText
    android:textColorHighlight="#7cff88"
/>

with a result such as this:

Displaying Placeholder Hints

You may want to set the hint for the EditText control to prompt a user for specific input with:

<EditText
    ...
    android:hint="@string/my_hint">
</EditText>

which results in:

Hints

Changing the bottom line color

Assuming you are using the AppCompat library, you can override the styles colorControlNormal, colorControlActivated, and colorControlHighlight:

<style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorControlNormal">#d32f2f</item>
    <item name="colorControlActivated">#ff5722</item>
    <item name="colorControlHighlight">#f44336</item>
</style>

If you do not see these styles applied within a DialogFragment, there is a known bug when using the LayoutInflater passed into the onCreateView() method.

The issue has already been fixed in the AppCompat v23 library. See this [[guide|Migrating-to-the-AppCompat-Library#overview]] about how to upgrade. Another temporary workaround is to use the Activity’s layout inflater instead of the one passed into the onCreateView() method:

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_fragment, container);
  }

Listening for EditText Input

Check out the [[basic event listeners|Basic-Event-Listeners#edittext-common-listeners]] cliffnotes for a look at how to listen for changes to an EditText and perform an action when those changes occur.

Displaying Floating Label Feedback

Traditionally, the EditText hides the hint message (explained above) after the user starts typing. In addition, any validation error messages had to be managed manually by the developer.

floating

Starting with Android M and the [[design support library|Design-Support-Library]], the TextInputLayout can be used to setup a floating label to display hints and error messages. First, wrap the EditText in a TextInputLayout:

<android.support.design.widget.TextInputLayout
    android:id="@+id/username_text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:ems="10"
        android:hint="Username" />

</android.support.design.widget.TextInputLayout>

Now the hint will automatically begin to float once the EditText takes focus as shown below:

floating

We can also use the TextInputLayout to display error messages using the setError and setErrorEnabled properties in the activity at runtime:

private void setupFloatingLabelError() {
    final TextInputLayout floatingUsernameLabel = (TextInputLayout) findViewById(R.id.username_text_input_layout);
    floatingUsernameLabel.getEditText().addTextChangedListener(new TextWatcher() {
        // ...
        @Override
        public void onTextChanged(CharSequence text, int start, int count, int after) {
            if (text.length() > 0 && text.length() <= 4) {
                floatingUsernameLabel.setError(getString(R.string.username_required));
                floatingUsernameLabel.setErrorEnabled(true);
            } else {
                floatingUsernameLabel.setErrorEnabled(false);
            }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

Here we use the addTextChangedListener to watch as the value changes to determine when to display the error message or revert to the hint.

Adding Character Counting

TextInputLayout since the announcement of support design library v23.1 also can expose a character counter for an EditText defined within it. The counter will be rendered below the EditText and can change colors of both the line and character counter if the maximum number of characters has been exceeded:

The TextInputLayout simply needs to define app:counterEnabled and app:CounterMaxLength in the XML attributes. These settings can also be defined dynamically through setCounterEnabled() and setCounterMaxLength():

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:counterEnabled="true"
    app:counterMaxLength="10"
    app:counterTextAppearance="@style/counterText"
    app:counterOverflowTextAppearance="@style/counterOverride">
    <EditText
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:hint="Username"
       android:layout_centerHorizontal="true"
       android:layout_centerVertical="true"
       android:ems="10"
       android:hint="Username" />
</android.support.design.widget.TextInputLayout>

Adding Password Visibility Toggles

NOTE: You must have support library 24.2.0 or higher to use this feature.

If you use an EditText with an input password type, you can also enable an icon that can show or hide the entire text using the passwordToggleEnabled attribute. You can also change the default eye icon with passwordToggleDrawable attribute or the color hint using the passwordToggleTint attribute. See the TextInputLayout attributes for more details.

<android.support.design.widget.TextInputLayout
        android:id="@+id/username_text_input_layout"
        app:passwordToggleEnabled="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/etUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:ems="10"
            android:inputType="textPassword"
            android:hint="Username" />

    </android.support.design.widget.TextInputLayout>

Styling TextInputLayout

Make sure you have the app namespace (xmlns:app="http://schemas.android.com/apk/res-auto" defined in your outer layout. You can type appNS as a shortcut in Android Studio to be declared.

The hint text can be styled by defining app:hintTextAppearance, and the error text can be changed with app:errorTextAppearance. The counter text and overflow text can also have their own text styles by defining app:counterTextAppearance and app:counterOverflowTextAppearance. We can use textColor, textSize, and fontFamily to help change the color, size, or font:

<style name="counterText">
  <item name="android:textColor">#aa5353cc</item>
</style>

<style name="counterOverride">
  <item name="android:textColor">#ff0000</item>
</style>

Providing Auto-complete

Check out the official text fields guide for a step-by-step on how to setup autocomplete for the entry.

ImageView

Typically, images are displayed using the built-in image view. This view takes care of the loading and optimizing of the image, freeing you to focus on app-specific details like the layout and content.

In this guide, we will take a look at how to use an ImageView, how to manipulate bitmaps, learn about the different density folders and more.

Usage

At the simplest level, an ImageView is simply a view you embed within an XML layout that is used to display an image (or any drawable) on the screen. The ImageView looks like this in res/layout/activity_main.xml:

<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"
    android:src="@drawable/my_image" />

The ImageView handles all the loading and scaling of the image for you. Note the scaleType attribute which defines how the images will be scaled to fit in your layout. In the example, using scaleType “center”, the image will be displayed at its native resolution and centered in the view, regardless of how much space the view consumes.

Sizing ImageView Controls

By default, contents of an ImageView control are of a certain size – usually the size of the image dimensions. They can also be bounded by their layout_width and layout_height attributes:

<ImageView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:scaleType="fitXY"
    ...
/>

The scaleType above has been set to fitXY which sets the height and the width up or down to fit the maximum dimensions specified.

Fixing the width and height however means that the proportions of the width and height of the original image, known as the aspect ratio, will be altered. We can take advantage of the adjustViewBounds parameter to preserve this aspect ratio. However, we must either allow the height and/or width to be adjustable (i.e. by using maxWidth and using wrap_content for the dimension). Otherwise, the dimensions cannot be readjusted to meet the required aspect ratio.

<ImageView
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"
    android:adjustViewBounds="true"
    ...
/>

By combining these properties together we can control the rough size of the image and still adjust the image according to the proper aspect ratio.

We can also size an ImageView at runtime within our Java source code by modifying the width or height inside getLayoutParams() for the view:

imageView.getLayoutParams().height = 100; // OR
imageView.getLayoutParams().width = 100;

In certain cases, the image needs to be scaled to fit the parent view’s width and the height should be adjusted proportionally. We can achieve this using an extended ResizableImageView class as described in the post.

Scale Types

An ImageView can display an image differently based on the scaleType provided. Above we discussed the fitXY type along with adjustViewBounds to match the aspect ratio of the drawable. The following is a list of all the most common types:

Scale Type Description
center Displays the image centered in the view with no scaling.
centerCrop Scales the image such that both the x and y dimensions are greater than or equal to the view, while maintaining the image aspect ratio; centers the image in the view.
centerInside Scales the image to fit inside the view, while maintaining the image aspect ratio. If the image is already smaller than the view, then this is the same as center.
fitCenter Scales the image to fit inside the view, while maintaining the image aspect ratio. At least one axis will exactly match the view, and the result is centered inside the view.
fitStart Same as fitCenter but aligned to the top left of the view.
fitEnd Same as fitCenter but aligned to the bottom right of the view.
fitXY Scales the x and y dimensions to exactly match the view size; does not maintain the image aspect ratio.
matrix Scales the image using a supplied Matrix class. The matrix can be supplied using the setImageMatrix method. A Matrix class can be used to apply transformations such as rotations to an image.

Note: The fitXY scale type allows you to set the exact size of the image in your layout. However, be mindful of potential distortions of the image due to scaling. If you’re creating a photo-viewing application, you will probably want to use the center or fitCenter scale types.

Refer to this ImageView ScaleType visual guide for additional reference. Remember that if you wish to match the aspect ratio of the actual drawable, adjustViewBounds=true must be declared along with not defining an explicit width and/or height.

Supporting Multiple Densities

Since Android has so many different screen sizes, resolutions and densities, there is a [[powerful system for selecting the correct image asset|Understanding-App-Resources#introducing-alternate-resources]] for the correct device. There are specific drawable folders for each device density category including: ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high). Notice that every app has folders for image drawables such as drawable-mdpi which is for “medium dots per inch”.

To create alternative bitmap drawables for different densities, you should follow the 3:4:6:8 scaling ratio between the four generalized densities. Refer to the chart below:

| Density | DPI | Example Device | Scale | Pixels | |——— |—- | —————-| —— | ———- | | ldpi | 120 | Galaxy Y | 0.75x | 1dp = 0.75px | | mdpi | 160 | Galaxy Tab | 1.0x | 1dp = 1px | | hdpi | 240 | Galaxy S II | 1.5x | 1dp = 1.5px | | xhdpi | 320 | Nexus 4 | 2.0x | 1dp = 2px | | xxhdpi | 480 | Nexus 5 | 3.0x | 1dp = 3px | | xxxhdpi | 640 | Nexus 6 | 4.0x | 1dp = 4px |

This means that if you generate a 100x100 for mdpi (1x baseline), then you should generate the same resource in 150x150 for hdpi (1.5x), 200x200 image for xhdpi devices (2.0x), 300x300 image for xxhdpi (3.0x) and a 75x75 image for ldpi devices (0.75x). See these density guidelines for additional details.

Densities

Final Android Resizer

To resize images more easily, check out the Final Android Resizer by downloading and running this JAR.

final resizer

This handy utility allows us to select a resources directory, choose an extra high density image and the tool will automatically generate the corresponding lower size images for us and place the subfolders inside the generated res-drawable diretory within the actual res folder in your project as the example shows below in “Project” view (left) and the default “Android” view (right):

 

Refer to the screens support reference for a more detailed look at supporting a wide range of devices. Also check out the iconography guide for more details.

Mipmaps and Drawables

Starting with Android 4.3, there is now an option to use the res/mipmap folder to store “mipmap” images. Mipmaps are most commonly used for application icons such as the launcher icon. To learn more about the benefits of mipmaps be sure to check out the mipmapping for drawables post.

Mipmap image resources can then be accessed using the @mipmap/ic_launcher notation in place of @drawable. Placing icons in mipmap folders (rather than drawable) is considered a best practice because they can often be used at resolutions different from the device’s current density. For example, an xxxhdpi app icon might be used on the launcher for an xxhdpi device. Review this post about preparing for the Nexus 6 which explains in more detail.

Working with Bitmaps

We can change the bitmap displayed in an ImageView to a drawable resource with:

ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageResource(R.drawable.test2);

or to any arbitrary bitmap with:

ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);

Scaling a Bitmap

If we need to resize a Bitmap, we can call the createScaledBitmap method to resize any bitmap to our desired width and height:

// Load a bitmap from the drawable folder
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
// Resize the bitmap to 150x100 (width x height)
Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, 150, 100, true);
// Loads the resized Bitmap into an ImageView
ImageView image = (ImageView) findViewById(R.id.test_image);
image.setImageBitmap(bMapScaled);

You often want to resize a bitmap but preserve the aspect ratio using a BitmapScaler utility class with code like this:

public class BitmapScaler
{
	// Scale and maintain aspect ratio given a desired width
	// BitmapScaler.scaleToFitWidth(bitmap, 100);
	public static Bitmap scaleToFitWidth(Bitmap b, int width)
	{
		float factor = width / (float) b.getWidth();
		return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
	}


	// Scale and maintain aspect ratio given a desired height
	// BitmapScaler.scaleToFitHeight(bitmap, 100);
	public static Bitmap scaleToFitHeight(Bitmap b, int height)
	{
		float factor = height / (float) b.getHeight();
		return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
	}

	// ...
}

In other cases, you may want to determine the device height or width in order to resize the image accordingly. Copy this DeviceDimensionsHelper.java utility class to DeviceDimensionsHelper.java in your project and use anywhere that you have a context to determine the screen dimensions:

// Get height or width of screen at runtime
int screenWidth = DeviceDimensionsHelper.getDisplayWidth(this);
// Resize a Bitmap maintaining aspect ratio based on screen width
BitmapScaler.scaleToFitWidth(bitmap, screenWidth);

Check out this source for more information on how to scale a bitmap based instead on relative device width and height.

Note: Doing any type of scaling of images results in the loss of EXIF metadata that includes info such as camera, rotation, date/time of the photo taken. While there are workarounds to transfer this data after the image has been copied, there are current limitations. If you need this info or wish to upload it to some site, you should send the original file and not the downsampled version.

Displaying SVG Images

Using a third party library called svg-android we can actually display resolution and density independent SVG images.

// Parse an SVG resource from the "raw" resource folder
SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android);
// Fix issue with renderer on certain devices
myImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// Get a drawable from the parsed SVG and set it as the drawable for the ImageView
myImageView.setImageDrawable(svg.createPictureDrawable());

See the official tutorial for more details.

Loading Images from the network

Loading images from the network is a challening task and the best way is to use libraries. The most popular libraries are :

Install the libraries from Nuget and follow the getting started guide to start using them.

ImageButton

A button that displays an image and its clickable.

<ImageButton
    android:id="@+id/photo_image_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop"
    android:src="@drawable/beach" />

RadioButton

Radio buttons allow the user to select one option from a set. You should use radio buttons for optional sets that are mutually exclusive if you think that the user needs to see all available options side-by-side. If it’s not necessary to show all options side-by-side, use a spinner instead.

Radio Buttons

To create each radio button option, create a RadioButton in your layout. However, because radio buttons are mutually exclusive, you must group them together inside a RadioGroup. By grouping them together, the system ensures that only one radio button can be selected at a time.

<RadioGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton
        android:id="@+id/yes_radio_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Yes"
        android:checked="true" />
    <RadioButton
        android:id="@+id/no_radio_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No"
        android:textAppearance="?android:textAppearanceMedium" />
    <RadioButton
        android:id="@+id/maybe_radio_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Maybe"
        android:textAppearance="?android:textAppearanceSmall" />
</RadioGroup>

Attaching Click Event

The radio button have a onClick event. We can attach the event to the buttons in code as follows :

public void onRadioButtonClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
    
    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radio_pirates:
            if (checked)
                // Pirates are the best
            break;
        case R.id.radio_ninjas:
            if (checked)
                // Ninjas rule
            break;
    }
}

Changing the State

We can change the state of the radio button by using the toggle() method.

View

A plain rectangle that can be used as a divider.

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#CCC" />

Spinner

Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.

Spinner

<Spinner
    android:id="@+id/sort_by_spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Populate Spinner with choices with XML

You can populate the Spinner using a string-array resource. Create a file the Resources\Values folder and call it array.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="cities">
        <item>Home</item>
        <item>Work</item>
        <item>Other</item>
        <item>Custom</item>
    </string-array>
</resources>

Now you can populate the entries for the spinner using the data from the xml file.

<Spinner
    android:entries="@array/cities"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Spinner Mode

The spinner by default displays a dropdown, but it can be changed to show a dialog using the android:spinnerMode="dialog".

Populate Spinner with code

To populate the spinner in code, you will need to create a custom array adapter, then bind the array adapter to the spinner or create it using an existing xml file with a string array.

Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.planets_array, android.R.layout.simple_spinner_dropdown_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_custom_layout);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);

Getting and Setting Values

Get the selected item out a spinner using:

String value = spinner.getSelectedItem().toString();

Setting spinner item based on value (rather than item position):

public void setSpinnerToValue(Spinner spinner, String value) {
	int index = 0;
	SpinnerAdapter adapter = spinner.getAdapter();
	for (int i = 0; i < adapter.getCount(); i++) {
		if (adapter.getItem(i).equals(value)) {
			index = i;
			break; // terminate loop
		}
	}
	spinner.setSelection(index);
}

Customizing Spinner Items

Changing text size on the <Spinner> tag has no effect on the actual dropdown items. To change their styles, you need to create a custom array adapter and layout file. First, you should create a spinner_item1.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style:"@style/spinner_dropdown_style1"
    android:textColor="#ff0000" />

Define your style to inherit from Widget.AppCompat.DropDownItem.Spinner so that it will inherit the correct spacing for dropdown items. Otherwise, you may notice the dropdown items are too closely spaced or not enough margin to the left-hand side:

<style name="spinner_dropdown_style_theme1" parent="Widget.AppCompat.DropDownItem.Spinner">
     <item name="android:textColor">@android:color/white</item>
     <item name="android:background">#507B91</item>
</style>

You then bind the string array of items to the layout:

ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, R.layout.spinner_item);
spinner.setAdapter(adapter);

CheckBox

Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list.

<CheckBox
    android:id="@+id/notify_me_checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/notify_me"
    android:textAppearance="?android:textAppearanceMedium" />

Responding to Events

We can access whether or not a checkbox is checked with:

CheckBox checkCheese = (CheckBox) findViewById(R.id.checkbox_cheese);
// Check if the checkbox is checked
boolean isChecked = checkCheese.isChecked();
// Set the checkbox as checked
checkCheese.setChecked(true);

and in our activity, we can manage checkboxes using a checked listener with OnCheckedChangeListener as below

// Defines a listener for every time a checkbox is checked or unchecked
CompoundButton.OnCheckedChangeListener checkListener = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton view, boolean checked) {
        // compoundButton is the checkbox
        // boolean is whether or not checkbox is checked
        // Check which checkbox was clicked
        switch(view.getId()) {
            case R.id.checkbox_meat:
                if (checked) {
                    // Put some meat on the sandwich
                } else {
                    // Remove the meat
                }
                break;
            case R.id.checkbox_cheese:
                if (checked) {
                    // Cheese me
                } else {
                    // I'm lactose intolerant
                }
                break;
          }
    }
};

// This actually applies the listener to the checkboxes 
// by calling `setOnCheckedChangeListener` on each one
public void setupCheckboxes() {
    Checkbox checkCheese = (Checkbox) findViewById(R.id.checkbox_cheese);
    Checkbox checkMeat = (Checkbox) findViewById(R.id.checkbox_meat);
    checkCheese.setOnCheckedChangeListener(checkListener);
    checkMeat.setOnCheckedChangeListener(checkListener);
}

Switch

On/off switch that can you drag to the right or left or just tap to toggle. SwitchCompat is a version of the Switch widget which runs on devices back to API 7

<Switch
    android:id="@+id/backup_photos_switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/auto_backup_photos"
    android:textAppearance="?android:textAppearanceSmall" />

For backwards compatibility use SwitchCompat. On older devices, the control is called a Togglebutton.

<android.support.v7.widget.SwitchCompat
    android:checked="true"
    android:id="@+id/backup_photos_switch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Backup photos automatically to the cloud when on wifi"
    android:textAppearance="?android:textAppearanceSmall" />

Responding to events

var backupPhotosSwitch = FindViewById<Switch>(Resource.Id.backup_photos_switch);
backupPhotosSwitch.CheckedChange +=  (object sender, CompoundButton.CheckedChangeEventArgs e) => { 
    Console.WriteLine($"Switch is {e.IsChecked}");
};

SeekBar

Displays progress and allows you to drag the handle anywhere in the bar e.g for music or video.

<SeekBar
    android:id="@+id/seek_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="100"
    android:progress="20" />

SeekBar Events

You handle the Progress event to get notified when the progress of the SeekBar changes.

var seekBar = FindViewById<SeekBar>(Resource.Id.seek_bar);
seekBar.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) => { 
    Console.WriteLine($"Progress is now {e.Progress}");
};

RatingBar

<RatingBar
    android:id="@+id/rating_bar"
    style="?android:attr/ratingBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numStars="5"
    android:rating="2.5"
    android:stepSize="0.5" />

RatingBar Events

You can use the RatingBarChange event to subscribe to changes in the RatingBar

var ratingBar = FindViewById<RatingBar>(Resource.Id.rating_bar);
ratingBar.RatingBarChange += (object sender, RatingBar.RatingBarChangeEventArgs e) => { 
    Console.WriteLine($"Rating is {e.Rating}");
};

ProgressBar

Loading spinner, used to show that something is running.

<ProgressBar
    android:id="@+id/loading_spinner"
    style="?android:progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Can also change the style to use a horizontal progressbar, use the style style=“?android:progressBarStyleHorizontal”

<ProgressBar
    android:id="@+id/progress_bar"
    style="?android:progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:indeterminate="false"
    android:max="100"
    android:progress="40"/>

SearchView

A search view that you type a query into.

    <SearchView
        android:id="@+id/search_viewer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:iconifiedByDefault="true"
        android:queryHint="Search photos" />

DatePickers

Video Summary

References