Android Custom Components

Android Custom Components

Android Custom Components – Implementing gown components in pre built-in components with extending subclass with own defined class

android custom components

Google android offers a great set of pre-built widgets like Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView etc. used immediately in your Google android program development, but there could be a situation if you are unhappy with existing operation of the available widgets. Android os offers you method of creating your own custom components which you are able to personalized to meet your requirements.

If you just need to make small alterations to a preexisting structure or widget, you can merely subclass the widget or structure and override its methods that will give you specific control over the looks and function of your screen element.

In this tutorial i will points out you how to generate custom Views and utilize them in the application using easy and simple steps.

android custom components

 

Creating a Simple Android Custom Components

Steps & Description

1- You use Android studio IDE to generate an Android request and name it as compoundview under a bundle com.androdevelopment.android.customview.compoundview as described in the Howdy World Example section.

2- Create an XML res/worth/attrs.xml data file to determine new attributes with their data sort.

3- Create src/ColorOptionsView.java data file and add the code to explain your custom element. It’ll expand LinearLayout and can have additional efficiency showing coloring substance . You shall provide characteristics parsing reasoning in of the constructors having AttributeSet as a parameter.

4- Modify res/design/activity_main.xml file and add the code to generate Colour substance view occasion along with few default qualities and new characteristics.

5- Run the application form to launch Android OS emulator and check the consequence of the changes done in the application form.

Now Create the given attributes file called attrs.xml in your res/values folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="Options">
      <attr name="titleText" format="string" localization="suggested" />
      <attr name="valueColor" format="color" />
   </declare-styleable>
</resources>

 

Change the layout file used by the activity to the following.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   xmlns:custom="http://schemas.android.com/apk/res/com.androdevelopment.android.view.compoundview"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:showDividers="middle"
   android:divider="?android:attr/listDivider"
   tools:context=".MainActivity" >
   
   <com.androdevelopment.android.view.compoundview.ColorOptionsView
      android:id="@+id/view1"
      android:layout_width="match_parent"
      android:layout_height="?android:attr/listPreferredItemHeight"
      android:background="?android:selectableItemBackground"
      android:onClick="onClicked"
      custom:titleText="Background color"
      custom:valueColor="@android:color/holo_green_light"/>

   <com.androdevelopment.android.view.compoundview.ColorOptionsView
      android:id="@+id/view2"
      android:layout_width="match_parent"
      android:layout_height="?android:attr/listPreferredItemHeight"
      android:background="?android:selectableItemBackground"
      android:onClick="onClicked"
      custom:titleText="Foreground color"
      custom:valueColor="@android:color/holo_orange_dark"/>

</LinearLayout>

 

Create the following java file called ColorOptionsView for your compound view.

package com.androdevelopment.android.customview.compoundview;

import com.androdevelopment.android.view.compoundview.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ColorOptionsView extends LinearLayout {
   private View mValue;
   private ImageView mImage;
   
   public ColorOptionsView(Context context, AttributeSet attrs) {
      super(context, attrs);
      
      TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.ColorOptionsView, 0, 0);
      String titleText = a.getString(R.styleable.ColorOptionsView_titleText);
      
      int valueColor = a.getColor(R.styleable.ColorOptionsView_valueColor,android.R.color.holo_blue_light);
      a.recycle();
      
      setOrientation(LinearLayout.HORIZONTAL);
      setGravity(Gravity.CENTER_VERTICAL);
      
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      inflater.inflate(R.layout.view_color_options, this, true);
      TextView title = (TextView) getChildAt(0);
      title.setText(titleText);
      
      mValue = getChildAt(1);
      mValue.setBackgroundColor(valueColor);
      mImage = (ImageView) getChildAt(2);
   }
   
   public ColorOptionsView(Context context) {
      this(context, null);
   }
   
   public void setValueColor(int color) {
      mValue.setBackgroundColor(color);
   }
   
   public void setImageVisible(boolean visible) {
      mImage.setVisibility(visible ? View.VISIBLE : View.GONE);
   }
} 

 

Change your Main activity java file to the following code and run your application


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed


package com.androdevelopment.android.customview.compoundview;

import com.androdevelopment.android.view.compoundview.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.activity_main, menu);
      return true;
   }
   
   public void onClicked(View view) {
      String text = view.getId() == R.id.view1 ? "Background" : "Foreground";
      Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
   }
} 

 

Run the application it should look like the following image

android custom components

Instantiate using code inside activity class

It’s very similar way of instantiating custom element how you instantiate built-in widget in your activity class. For instance you may use following code (given above)to instantiate defined custom component

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   
   DateView dateView = new DateView(this);
   setContentView(dateView);
}

 

Check Above code to comprehend how to Instantiate a simple Google android Custom Component using code in a activity.

Instantiate using Layout XML file

You utilize Layout XML to instantiate your built-in widgets customarily, same principle will apply on your custom widgets as well which means you can instantiate your custom aspect using Layout XML data file as discussed below. Here com.example.compoundview is the offer where you have put all the code related to DateView course and DateView is Java course name where you have put complete login of your custom element.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >
   
   <com.example.compoundview.DateView
      android:layout_width="match_parent"
      android:layout_height="wrap_content" 
      android:textColor="#fff"
      android:textSize="40sp"
      android:background="#000"/>
</RelativeLayout>

 

It’s important to notice here that people are employing all TextView features along with custom aspect without the change. Similar way you will be in a position to use all the situations, and methods along with DateView part.

Android Custom Components with Custom Attributes

We’ve seen how exactly we can extend efficiency of built-in widgets however in both the cases given above we noticed that extended element can employ all the default qualities of its parent class. But look at a situation when you wish to build your own feature from scratch. Below is a straightforward procedure to generate and use new characteristics for Google android Custom components. Consider you want to introduce three capabilities and will utilize them as given below

<com.example.compoundview.DateView
   android:layout_width="match_parent"
   android:layout_height="wrap_content" 
   android:textColor="#fff"
   android:textSize="40sp"
   custom:delimiter="-"
   custom:fancyText="true"/>

 

Android Custom Components – Step 1

The first step to permit us to make use of our custom attributes is to identify them in a fresh xml file under res/worth/ and call it attrs.xml. Let’s take a glance on a good example attrs.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="DateView">
   <attr name="delimiter" format="string"/>
   <attr name="fancyText" format="boolean"/>
   </declare-styleable>
</resources>

 

Here the name=value is exactly what you want to use inside our Layout XML as attribute, and the format=type is the sort of attribute.

Android Custom Components – Step 2

Your next step is to read these attributes from Design XML data file and establish them for the element. This logic shall go ahead the constructors that get handed an AttributeSet, since that is exactly what provides the XML attributes. To learn the values in the XML, you will need to first produce a TypedArray from the AttributeSet, then use that to learn and establish the prices as shown in the below example code

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DateView);

final int N = a.getIndexCount();
for (int i = 0; i < N; ++i)
{
   int attr = a.getIndex(i);
   switch (attr)
   {
      case R.styleable.DateView_delimiter:
      String delimiter = a.getString(attr);
      
      //...do something with delimiter...
      break;
      
      case R.styleable.DateView_fancyText:
      boolean fancyText = a.getBoolean(attr, false);
      
      //...do something with fancyText...
      break;
   }
}
a.recycle();

 

Android Custom Components – Step 3

Finally you can use your defined attributes in your Layout XML file as follows

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   xmlns:custom="http://schemas.android.com/apk/res/com.example.compoundview"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >
   
   <com.example.compoundview.DateView
      android:layout_width="match_parent"
      android:layout_height="wrap_content" 
      android:textColor="#fff"
      android:textSize="40sp"
      custom:delimiter="-"
      custom:fancyText="true"/>

</RelativeLayout>

 

The top part is xmlns:custom=”http://schemas.android.com/apk/res/com.example.compoundview”. Remember that http://schemas.android.com/apk/res/ will stay as is, but previous part will be placed to your offer name and also which you can use anything after xmlns, in this example I used custom, nevertheless, you might use any true name you prefer.

 

 

 


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed