23.07.2015 Views

Android Tutorial

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Following example shows you how to define a simple <strong>Android</strong> custom component with custom attributes.<br />

Step Description<br />

1<br />

You will use Eclipse IDE to create an <strong>Android</strong> application and name it as DateViewDemounder a<br />

package com.example.dateviewdemo as explained in the Hello World Examplechapter.<br />

2 Create an XML res/values/attrs.xml file to define new attributes alongwith their data type.<br />

3<br />

4<br />

Create src/DateView.java file and add the code to define your custom component. It will extend TextView and<br />

will have additional functionality to show current date. You will provide attributes parsing logic in of the<br />

constructors having AttributeSet as a parameter.<br />

Modify res/layout/activity_main.xml file and add the code to create DateView instance along with few default<br />

attributes and new attributes.<br />

5 Run the application to launch <strong>Android</strong> emulator and verify the result of the changes done in the aplication.<br />

Following is the content of the modified main activity filesrc/com.example.dateviewdemo/MainActivity.java. This<br />

file can include each of the fundamental lifecycle methods.<br />

package com.example.dateviewdemo;<br />

import android.os.Bundle;<br />

import android.app.Activity;<br />

import android.view.Menu;<br />

public class MainActivity extends Activity {<br />

}<br />

@Override<br />

protected void onCreate(Bundle savedInstanceState) {<br />

super.onCreate(savedInstanceState);<br />

setContentView(R.layout.activity_main);<br />

}<br />

@Override<br />

public boolean onCreateOptionsMenu(Menu menu) {<br />

// Inflate the menu; this adds items to the<br />

// action bar if it is present.<br />

getMenuInflater().inflate(R.menu.main, menu);<br />

return true;<br />

}<br />

Following will be the content of res/values/attrs.xml file:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Following will be the content of new file src/com.example.dateviewdemo/DateView.java, which will have<br />

additional functionality to show current date:<br />

package com.example.dateviewdemo;<br />

TUTORIALS POINT<br />

Simply Easy Learning

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!