Monday, April 20, 2015
Reflection in Java Example
Manchu Bhargavi
12:42 AM
java
,
methods in reflection
,
reflection
,
reflection in java example
No comments
:
Hi,
Reflection.java :
Example.java :
Reflection in Java
Example :
Reflection
is most powerful concept. It is used to get classes and methods, interfaces,
fields, constructors, annotations in the runtime. Even if dono what are classes
and methods are available.
Reflection is language ability to inspect and dynamically call the
classes,methods,attrtitubes,etc at runtime.
Reflection in java is used to inspect and modify the
structure at runtime behavior of applications.
Syntax for Reflection
:
Method[] methods=myClass.class.getMethods();
For(Method method
:methods){
System.out.println(“Method =”method.getName());
}
Examples for
Reflection in classes :
1.Create the java Project in Eclipse
2.Create the java class called Reflection.java
package com.example.reflect;
public class Reflection {
private
int count=0;
public void result(){
System.out.println("The
reflection is used to get all methods and class in runtime");
}
public void
printMethods(String name){
System.out.println("this
method is shows with one param"+name);
}
public void printIntMethod(int
no){
System.out.println("All
methods in print methods are"+no);
}
public void
getAllMethods(){
System.out.println("This
is to get all methods");
}
public void setMethod(int
no){
no=count;
System.out.println("The
reflection method is"+no);
}
}
3. create the another class called Example.java
package com.example.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Example {
public static void main(String[] args) {
Method[] method =
Reflection.class.getDeclaredMethods();
Reflection rf = new Reflection();
//printing
all the methods from the another class durning runtime
System.out.println("start");
for
(Method me : method) {
System.out.println("The
methods are \t" + me);
}Method[]
mMethod=rf.getClass().getMethods();
//calling
the refelection method
try
{
System.out.println("here
only calling method will print");
mMethod[0].invoke(rf,
null);
System.out.println("Ending
method is as follows");
}
catch (IllegalAccessException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Exit")
} }
4.Run the application and check the output
Wednesday, August 20, 2014
Android Gallery Images using dots
Manchu Bhargavi
7:16 PM
Android galery images with dots
,
gallery image
,
images
,
images with dots using android
,
pagination dots in android
1 comment
:
Gallery Images using dots in Android :
This is an Example how to create dots while scrolling the images in Android
1. Create a Android Application project
2.After that create drawable folder under res and put all the images
3.create the ImageAdapter class that extends the BaseAdapter that implements all predefined methods and also create an constructor array of integers which storing imageids
ImageAdapter.java:
package com.example.galleryimage;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class ImageAdapter extends BaseAdapter {
private Context context;
public IamgeAdapter(Context c) {
// TODO Auto-generated constructor stub
this.context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return flowers.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image = new ImageView(context);
image.setImageResource(flowers[position]);
image.setScaleType(ScaleType.FIT_XY);
// image.setLayoutParams(new Gallery.LayoutParams(400, 400));
return image;
}
int[] flowers = { R.drawable.images2, R.drawable.img1, R.drawable.img2};
}
4.Then put these codings in MainActivity.java
MainActivity.java :
package com.example.galleryimage;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
Gallery gallery;
IamgeAdapter imageAdapter;
LinearLayout count_layout;
int count = 0;
static TextView page_text[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count_layout = (LinearLayout) findViewById(R.id.image_count);
gallery = (Gallery) findViewById(R.id.mygallery01);
imageAdapter = new IamgeAdapter(this);
gallery.setAdapter(imageAdapter);
count=gallery.getAdapter().getCount();
page_text = new TextView[count];
for (int i = 0; i < count; i++) {
page_text[i] = new TextView(this);
page_text[i].setText(".");
page_text[i].setTextSize(45);
page_text[i].setTypeface(null, Typeface.BOLD);
page_text[i].setTextColor(android.graphics.Color.GRAY);
count_layout.addView(page_text[i]);
}
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
for (int i = 0; i < count; i++) {
MainActivity.page_text[i].setTextColor(android.graphics.Color.GRAY);
}
MainActivity.page_text[position].setTextColor(android.graphics.Color.WHITE);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
5.put these code in activity_main.xml
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery_paging"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="vertical" >
<Gallery
android:id="@+id/mygallery01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<LinearLayout
android:id="@+id/image_count"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:gravity="center" >
</LinearLayout>
</RelativeLayout>
Screenshots:
DOWNLOAD CODE
This is an Example how to create dots while scrolling the images in Android
1. Create a Android Application project
2.After that create drawable folder under res and put all the images
3.create the ImageAdapter class that extends the BaseAdapter that implements all predefined methods and also create an constructor array of integers which storing imageids
ImageAdapter.java:
package com.example.galleryimage;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class ImageAdapter extends BaseAdapter {
private Context context;
public IamgeAdapter(Context c) {
// TODO Auto-generated constructor stub
this.context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return flowers.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image = new ImageView(context);
image.setImageResource(flowers[position]);
image.setScaleType(ScaleType.FIT_XY);
// image.setLayoutParams(new Gallery.LayoutParams(400, 400));
return image;
}
int[] flowers = { R.drawable.images2, R.drawable.img1, R.drawable.img2};
}
4.Then put these codings in MainActivity.java
MainActivity.java :
package com.example.galleryimage;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
Gallery gallery;
IamgeAdapter imageAdapter;
LinearLayout count_layout;
int count = 0;
static TextView page_text[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count_layout = (LinearLayout) findViewById(R.id.image_count);
gallery = (Gallery) findViewById(R.id.mygallery01);
imageAdapter = new IamgeAdapter(this);
gallery.setAdapter(imageAdapter);
count=gallery.getAdapter().getCount();
page_text = new TextView[count];
for (int i = 0; i < count; i++) {
page_text[i] = new TextView(this);
page_text[i].setText(".");
page_text[i].setTextSize(45);
page_text[i].setTypeface(null, Typeface.BOLD);
page_text[i].setTextColor(android.graphics.Color.GRAY);
count_layout.addView(page_text[i]);
}
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
for (int i = 0; i < count; i++) {
MainActivity.page_text[i].setTextColor(android.graphics.Color.GRAY);
}
MainActivity.page_text[position].setTextColor(android.graphics.Color.WHITE);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
5.put these code in activity_main.xml
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery_paging"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="vertical" >
<Gallery
android:id="@+id/mygallery01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<LinearLayout
android:id="@+id/image_count"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:gravity="center" >
</LinearLayout>
</RelativeLayout>
Screenshots:
DOWNLOAD CODE
Monday, March 3, 2014
Custom Toast and Alert Dialog in Android Example
Manchu Bhargavi
9:12 PM
android
,
Android Alert Dialog
,
Custom Toast
,
CustomToast Android
,
Dialog
,
Toast
No comments
:
Hi,
This is an Example for Custom toast and Alert Dialog in Android Example. We can use this Alert and Custom Toast Project in Android Example.
Using handler that receives messages from the thread and update the progress.
we can create that show Toast and show Dialog method in Main Activity class.
// sending error message to handler
public void showToast(int show_toast, int error, int error_layout,
String message) {
Message msg = handler.obtainMessage();
msg.what = show_toast;
msg.arg1 = error;
msg.arg2 = error_layout;
msg.obj = message;
msg.sendToTarget();
}
// sending success message to handler
public void showAlert(int show_alert, String message2) {
Message msg = handler.obtainMessage();
msg.what = show_alert;
msg.obj = message2;
msg.sendToTarget();
}
Output is shown below
Download this project
This is an Example for Custom toast and Alert Dialog in Android Example. We can use this Alert and Custom Toast Project in Android Example.
Using handler that receives messages from the thread and update the progress.
we can create that show Toast and show Dialog method in Main Activity class.
// sending error message to handler
public void showToast(int show_toast, int error, int error_layout,
String message) {
Message msg = handler.obtainMessage();
msg.what = show_toast;
msg.arg1 = error;
msg.arg2 = error_layout;
msg.obj = message;
msg.sendToTarget();
}
// sending success message to handler
public void showAlert(int show_alert, String message2) {
Message msg = handler.obtainMessage();
msg.what = show_alert;
msg.obj = message2;
msg.sendToTarget();
}
Download this project
Tuesday, January 28, 2014
How to Use PrePopulated SQLite Database in Android
Manchu Bhargavi
6:17 AM
android
,
exixting databse in android
,
per-populated database
,
sqlite
,
sqlite db in android
,
sqlitedb
2 comments
:
Here we can create SQLite database is created at runtime. we can use this an existing database in Android App
Creating the Pre-Populated Database :
To create a Separate database using SQLite Database Browser we can download the SQLManager
addon on Firefox
Using this SQLite Manager create a sample.sqlite3 file with one table called friends. which shows list of friends and has two fields: id and name
To make your database work correctly on a device you have to included two modifications.
1. Rename the id field of your own table to "_id" you can done this with modify the table and then choosing the necessary table and field names.
2. Add the android_metadata table.To do that open the Execute SQL tab and run this both command
into the SQL String field:
CREATE TABLE android_metadata (locale_TEXT);
INSERT INTO android_metadata VALUES ('en_US');
click the execute query button and now you can export the database and located in assests folder in Android Project.
Implementing the ExternalDbOpenHelper class
This class is inherited from SOLiteOpenHelper. The application database are stored in the data/data/<name of your package>/databases/ folder on your device.
Note: Export the database from SQLManager and put in assests folder in Android Project.
Creating the Pre-Populated Database :
To create a Separate database using SQLite Database Browser we can download the SQLManager
addon on Firefox
Using this SQLite Manager create a sample.sqlite3 file with one table called friends. which shows list of friends and has two fields: id and name
To make your database work correctly on a device you have to included two modifications.
1. Rename the id field of your own table to "_id" you can done this with modify the table and then choosing the necessary table and field names.
2. Add the android_metadata table.To do that open the Execute SQL tab and run this both command
into the SQL String field:
CREATE TABLE android_metadata (locale_TEXT);
INSERT INTO android_metadata VALUES ('en_US');
click the execute query button and now you can export the database and located in assests folder in Android Project.
Implementing the ExternalDbOpenHelper class
This class is inherited from SOLiteOpenHelper. The application database are stored in the data/data/<name of your package>/databases/ folder on your device.
Note: Export the database from SQLManager and put in assests folder in Android Project.
Download this Project
Thursday, January 16, 2014
How to Swipe the Images in Android
Manchu Bhargavi
9:49 PM
android
,
how to swipe image in android
,
image
,
imageswipe
,
imageswipe in android
3 comments
:
Hi,
This is an example for swipe the image in android using pager adapter
1. create a xml file called activity_main.xml
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
2. create a Java class called MainActivity.class
using Imageadapter class create view for page adapter and override a method called instantiateItem
MainActivity.class :
package com.example.imageswipe;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7
};
ImageAdapter(Context context)
{
this.context=context;
}
@Override
public int getCount() {
return GalImages.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
3. Here the output is shown below
This is an example for swipe the image in android using pager adapter
1. create a xml file called activity_main.xml
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
2. create a Java class called MainActivity.class
using Imageadapter class create view for page adapter and override a method called instantiateItem
MainActivity.class :
package com.example.imageswipe;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4,
R.drawable.img5,
R.drawable.img6,
R.drawable.img7
};
ImageAdapter(Context context)
{
this.context=context;
}
@Override
public int getCount() {
return GalImages.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
3. Here the output is shown below
Friday, January 10, 2014
How To create DatePickerDialog Example in Android
Manchu Bhargavi
9:09 PM
datedialog
,
datelistener
,
datepickerdialog
,
how to create an dilaog
,
ondatset
16 comments
:
Hi,
This is an Example for creating DatePickerDialog Example in Android
DatePicker Dialog is child class for AlertDialog.It is used to select Date.And the benefits of DatePickerDialog is appears as pre user request and after setting the date it automatically disappears.And it does not occupy any space in Activity.
Syntax for Create DatePickerDialog :
Create a DatePickerDailog class and the parameter of DatePickerDialog is Activity Context,Callback Listener,year,month,day.
Dialog dialog=new DatePickerDialog(context,callback,year,month,dayofMonth);
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="142dp"
android:text="StartDate"
android:textStyle="bold"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="42dp"
android:text="EndDate"
android:textStyle="bold"/>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_toLeftOf="@+id/startdate"
android:layout_toRightOf="@+id/textView1"
android:ems="10"
android:hint="Startdate" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignTop="@+id/textView2"
android:layout_toLeftOf="@+id/startdate"
android:hint="Enddate"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/startdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentRight="true"
android:background="@drawable/img" />
<Button
android:id="@+id/enddate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText2"
android:layout_toRightOf="@+id/editText2"
android:background="@drawable/img"
/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="submit" />
</RelativeLayout>
In the activity class I have created a constant DATE_DIALOG_ID
static final int DATE_DIALOG_ID=0;
It is unique id for the DatePickerDialog. It can be any number. Now we can discuss about showDatePickerDialog method
mstart_date.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_MONTH);
showDialog(START_DATE_DIALOG_ID);
}
});
First Iam getting current date status and storing to instance variables year,month,day. To display a dialog window we are using showDialog method and Iam also passing the unique id.
This showDialog method is comes from android.app.Activity class.
showDialog(START_DATE_DIALOG_ID);
when the showDialog method is called,the onCreateDialog method will be automatically called.
protected Dialog onCreateDialog(int id){
switch(id){
case START_DATE_DIALOG_ID:
return new DatePickerDialog(this,dataSetListener,year, month, day);
case END_DATE_DIALOG_ID:
return new DatePickerDialog(this,endSetListener,year, month, day);
}
return null;
}
In the onCreateDialog method. creating the DatePickerDialog. Then return it to the calling location and dialog will be displayed automatically.
In the DatePickerDialog constructor passing the value for year,month,day and passing the reference of DatePickerDialog.OnDateSetListener.
In OnDateSetListener is automatically called onDateSet method when user click the on Set button of date picker dialog.
onDateSet method assign the value for year,month,day and set the Text it.
private DatePickerDialog.OnDateSetListener dataSetListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
year=year;
month=monthOfYear;
day=dayOfMonth;
mstart_edt1.setText(day+" - "+(month+1)+" - "+year);
}
};
Iam calling setText method of EditText by passing the selected year,month and day
Here the output is shown below
.
This is an Example for creating DatePickerDialog Example in Android
DatePicker Dialog is child class for AlertDialog.It is used to select Date.And the benefits of DatePickerDialog is appears as pre user request and after setting the date it automatically disappears.And it does not occupy any space in Activity.
Syntax for Create DatePickerDialog :
Create a DatePickerDailog class and the parameter of DatePickerDialog is Activity Context,Callback Listener,year,month,day.
Dialog dialog=new DatePickerDialog(context,callback,year,month,dayofMonth);
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="19dp"
android:layout_marginTop="142dp"
android:text="StartDate"
android:textStyle="bold"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="42dp"
android:text="EndDate"
android:textStyle="bold"/>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_toLeftOf="@+id/startdate"
android:layout_toRightOf="@+id/textView1"
android:ems="10"
android:hint="Startdate" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignTop="@+id/textView2"
android:layout_toLeftOf="@+id/startdate"
android:hint="Enddate"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/startdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentRight="true"
android:background="@drawable/img" />
<Button
android:id="@+id/enddate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editText2"
android:layout_toRightOf="@+id/editText2"
android:background="@drawable/img"
/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="submit" />
</RelativeLayout>
MainActivity.java:
package com.example.datepickerexample;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends Activity {
Button mstart_date,mend_date;
private int year;
private int month;
private int day;
Calendar cal;
EditText mstart_edt1,mend_edt2;
static final int START_DATE_DIALOG_ID=0;
static final int END_DATE_DIALOG_ID=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mstart_edt1=(EditText)findViewById(R.id.editText1);
mend_edt2=(EditText)findViewById(R.id.editText2);
mstart_date=(Button)findViewById(R.id.startdate);
mend_date=(Button)findViewById(R.id.enddate);
mstart_date.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_MONTH);
showDialog(START_DATE_DIALOG_ID);
}
});
mend_date.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
cal = Calendar.getInstance();
year=cal.get(Calendar.YEAR);
month=cal.get(Calendar.MONTH);
day=cal.get(Calendar.DAY_OF_MONTH);
showDialog(END_DATE_DIALOG_ID);
}
});
}
protected Dialog onCreateDialog(int id){
switch(id){
case START_DATE_DIALOG_ID:
return new DatePickerDialog(this,dataSetListener,year, month, day);
case END_DATE_DIALOG_ID:
return new DatePickerDialog(this,endSetListener,year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener dataSetListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
year=year;
month=monthOfYear;
day=dayOfMonth;
mstart_edt1.setText(day+" - "+(month+1)+" - "+year);
}
};
private DatePickerDialog.OnDateSetListener endSetListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
year=year;
month=monthOfYear;
day=dayOfMonth;
mend_edt2.setText(day+" - "+(month+1)+" - "+year);
}
};
}
Here the explanation for Mainactivity.class
In the activity class I have created a constant DATE_DIALOG_ID
static final int DATE_DIALOG_ID=0;
It is unique id for the DatePickerDialog. It can be any number. Now we can discuss about showDatePickerDialog method
mstart_date.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
year=c.get(Calendar.YEAR);
month=c.get(Calendar.MONTH);
day=c.get(Calendar.DAY_OF_MONTH);
showDialog(START_DATE_DIALOG_ID);
}
});
First Iam getting current date status and storing to instance variables year,month,day. To display a dialog window we are using showDialog method and Iam also passing the unique id.
This showDialog method is comes from android.app.Activity class.
showDialog(START_DATE_DIALOG_ID);
when the showDialog method is called,the onCreateDialog method will be automatically called.
protected Dialog onCreateDialog(int id){
switch(id){
case START_DATE_DIALOG_ID:
return new DatePickerDialog(this,dataSetListener,year, month, day);
case END_DATE_DIALOG_ID:
return new DatePickerDialog(this,endSetListener,year, month, day);
}
return null;
}
In the onCreateDialog method. creating the DatePickerDialog. Then return it to the calling location and dialog will be displayed automatically.
In the DatePickerDialog constructor passing the value for year,month,day and passing the reference of DatePickerDialog.OnDateSetListener.
In OnDateSetListener is automatically called onDateSet method when user click the on Set button of date picker dialog.
onDateSet method assign the value for year,month,day and set the Text it.
private DatePickerDialog.OnDateSetListener dataSetListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
year=year;
month=monthOfYear;
day=dayOfMonth;
mstart_edt1.setText(day+" - "+(month+1)+" - "+year);
}
};
Iam calling setText method of EditText by passing the selected year,month and day
Here the output is shown below
.
Sunday, December 29, 2013
CircularImageView Using Custom View
Manchu Bhargavi
10:55 AM
android
,
circular gridview in android
,
circularimageview in android
,
customview
,
customview extends view class in android example
,
customview using circular image in android
,
imageview using gridview
20 comments
:
Hi,
This is an Example for CustomView extends View Class.
Introduction:
Own view typically classified as custom views and compound views.
compound views are constructor based on existing views with some predefined layout and logic
and it extends on View group class.
custom view extends view class and draw on themselves
Introduction:
Own view typically classified as custom views and compound views.
compound views are constructor based on existing views with some predefined layout and logic
and it extends on View group class.
custom view extends view class and draw on themselves
Creating custom view:
By extending viewclass or one of its subclass you can create your own view.It is responsible for measuring,layouting,drawing themselves and their child elements and also saving UI state and handling touch events.
Reason for creating view:
View are typically created to avoid repetition code
By extending viewclass or one of its subclass you can create your own view.It is responsible for measuring,layouting,drawing themselves and their child elements and also saving UI state and handling touch events.
Reason for creating view:
View are typically created to avoid repetition code
CutomView.class:
package com.example.circularImageview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.widget.ImageView;
public class CustomView extends ImageView
{
private int color;
private Paint paint;
private Rect rect;
private RectF rectF;
private Bitmap output;
private Canvas canvas;
private float roundPx;
public CustomView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(),getMeasuredWidth());
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
// TODO Auto-generated method stub
int targetWidth = 1000;
int targetHeight =630;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight) / 2,(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
Path.Direction.CCW);
//path.addCircle(50,50,50,Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}
}
MainActivity.java:
package com.example.circularImageview;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private LruCache<String, Bitmap> mMemoryCache;
GridView gd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gd=(GridView)findViewById(R.id.gridView1);
gd.setAdapter(new MyAdapter(this));
gd.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(),"your position is "+arg2, 4).show();
}
});
}
public class MyAdapter extends BaseAdapter
{
private List<Item> items=new ArrayList<Item>();
private LayoutInflater inflator;
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
inflator=LayoutInflater.from(context);
items.add(new Item("nature1",R.drawable.img1));
items.add(new Item("nature2",R.drawable.img2));
items.add(new Item("nature3",R.drawable.img3));
items.add(new Item("nature4",R.drawable.img4));
items.add(new Item("nature5", R.drawable.img5));
items.add(new Item("nature6",R.drawable.img2));
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return items.get(position).drawableId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View v=convertView;
ImageView img1;
TextView txt1;
if(v==null)
{
v=inflator.inflate(R.layout.grid_item,parent,false);
v.setTag(R.id.picture,v.findViewById(R.id.picture));
v.setTag(R.id.text,findViewById(R.id.text));
}
img1=(ImageView)v.findViewById(R.id.picture);
txt1=(TextView)v.findViewById(R.id.text);
Item item=(Item)getItem(position);
// final String imageKey = String.valueOf(item.drawableId);
CustomView cv=new CustomView(MainActivity.this);
//final Bitmap bitmap = mMemoryCache.get(imageKey);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), item.drawableId);
img1.setImageBitmap(cv.getRoundedShape(bmp));
// img1.setImageResource(item.drawableId);
txt1.setText(item.name);
return v;
}
}
private class Item
{
final String name;
final int drawableId;
Item(String name,int drawableId)
{
this.name=name;
this.drawableId=drawableId;
}
}
}
activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/FrameLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:gravity="center"
android:stretchMode="columnWidth"
android:numColumns="auto_fit"
>
</GridView>
</FrameLayout>
list.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
>
</ListView>
</RelativeLayout>
Here the Output is shown below
Subscribe to:
Posts
(
Atom
)