Tag Archives: Android

TabWidget in Android UI Control

TabWidget is an Android Control which represents each page in the parents tab collection.

the container object for this widget is tab host, When the user selects a tab, this object sent a message to the parent container(tab host), to tell is to switch the displayed page. The container tab host is used to add labels, add call back handlers, and manage call backs.

Android tab host provides a nice way to present multiple things on a single screen, in order to use tabs we have to set two things to the tab:

1) Tab Indicator : text to show on tab, done by “setIndicator(“Tab Name”);”

2) Tab Content : This is used to set the activity that will be opened when the user selects/clicks a particular tab.

this is set by “setContent(“activity object”);”

TabWidget

Activity_Main.xml :

<?xml version=”1.0″ encoding=”utf-8″?>

<TabHost xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:id=”@android:id/tabhost”>

<LinearLayout android:id=”@+id/LinearLayout01″
android:orientation=”vertical”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>

<TabWidget android:id=”@android:id/tabs”
android:layout_height=”wrap_content”
android:layout_width=”fill_parent”>
</TabWidget>

<FrameLayout android:id=”@android:id/tabcontent”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>
</FrameLayout>

</LinearLayout>

</TabHost>

Screen1.xml :

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/LinearLayout01″
android:background=”#FFFF0000″
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>

<Button android:id=”@+id/btnScreen1″
android:layout_width=”150dip”
android:layout_height=”40dip”
android:text=”First Screen” />

</RelativeLayout>

Screen2.xml :

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/LinearLayout02″
android:background=”#FF00FF00″
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>

<Button android:id=”@+id/btnScreen2″
android:layout_width=”150dip”
android:layout_height=”40dip”
android:text=”Second Screen” />

</RelativeLayout>

Screen3.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/LinearLayout02″
android:background=”#FF0000FF”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>

<Button android:id=”@+id/btnScreen3″
android:layout_width=”150dip”
android:layout_height=”40dip”
android:text=”Third Screen” />

</RelativeLayout>

Screen4.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/LinearLayout02″
android:background=”#FFbbbbbb”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent”>

<Button android:id=”@+id/btnScreen4″
android:layout_width=”150dip”
android:layout_height=”40dip”
android:text=”fourth Screen” />

</RelativeLayout>

Main_Actvity.java :


package com.example.tabwidget;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class MainActivity extends TabActivity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

// create the TabHost that will contain the Tabs
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

TabSpec tab1 = tabHost.newTabSpec(“First Tab”);
TabSpec tab2 = tabHost.newTabSpec(“Second Tab”);
TabSpec tab3 = tabHost.newTabSpec(“Third tab”);
TabSpec tab4 = tabHost.newTabSpec(“Fourth tab”);

// Set the Tab name and Activity
// that will be opened when particular Tab will be selected

tab1.setIndicator(“”, getResources().getDrawable(R.drawable.ic_launcher));
tab1.setContent(new Intent(this,Tab1Activity.class));

tab2.setIndicator(“”, getResources().getDrawable(R.drawable.ic_launcher));
tab2.setContent(new Intent(this,Tab2Activity.class));

tab3.setIndicator(“”, getResources().getDrawable(R.drawable.ic_launcher));
tab3.setContent(new Intent(this,Tab3Activity.class));

tab4.setIndicator(“”, getResources().getDrawable(R.drawable.ic_launcher));
tab4.setContent(new Intent(this,Tab4Activity.class));

/** Add the tabs to the TabHost to display. */
tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.addTab(tab3);
tabHost.addTab(tab4);

}
}

 

Tab1_Activity.java :

package com.example.tabwidget;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;

public class Tab1Activity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
}
}

 

Tab2_Actvity.java :

package com.example.tabwidget;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;

public class Tab2Activity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
}
}

 

Tab3Activity.java :

package com.example.tabwidget;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;
public class Tab3Activity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

super.onCreate(savedInstanceState);
setContentView(R.layout.screen3);
}
}

 

Tab4Actvity.java :

package com.example.tabwidget;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;
public class Tab4Activity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

super.onCreate(savedInstanceState);
setContentView(R.layout.screen4);
}
}

SlidingDrawer in Android UI Control

SlidingDrawer

SlidingDrawer is a control which hides content (controls and text level) out of the screen and allows the user to drag a handle to bring the content on the screen.

SlidingDrawer can be used vertically or horizontally. A special Widget composed of two children views:

1) the handle: this is used to be drag by the user and content attached to the handle.

2) the content:the content layout is attached to the handle and drag on to the screen when the user pulls the handle.

sliding drawer should be used as an overlay inside layouts, this means that sliding drawer should only be used inside of a frame layout or a relative layout. the size of the sliding drawer defines how much space the content will occupy one slide out.

inside a xml layout sliding drawer must define the ID of the handle and the content layout.

Attributes of sliding drawer:-

a) android:allowSingleTab : it is used to set weather the drawer can be open/close by a single tab on a handle.

b) android:animateOnClick : this attribute sets weather the drawer should be open/close with an animation effect when the     user click on the handle.

c) android:bottomOffset : this sets the extra off sets for the handle at the bottom of the SlidingDrawer.

d) android:content : this attribute act as an identifier for the child that represents the drawers content.

e) android:handle : this attribute act as an identifier for the child that represents the drawers handle.

f) android:orientation : this sets the orientation of the sliding drawer.

g) android:topOffset : this sets the extra off sets for the handle at the top of the SlidingDrawer.

 

.xml file: 

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@+id/LinearLayout01″
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:background=”@drawable/androidpeople”>
<SlidingDrawer android:id=”@+id/SlidingDrawer”
android:layout_alignParentBottom=”true”
android:layout_width=”fill_parent”
android:layout_height=”250dip”
android:handle=”@+id/slideHandleButton”
android:content=”@+id/contentLayout”
android:padding=”10dip”
android:orientation=”vertical”>

<Button android:id=”@+id/slideHandleButton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:background=”@drawable/closearrow” />

<LinearLayout android:id=”@+id/contentLayout”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:background=”#c1cdcd”
android:gravity=”center|top”
android:orientation=”vertical”
android:padding=”10dip” >

<Button android:id=”@+id/Button01″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:background=”@drawable/download” />

<Button android:id=”@+id/Button02″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:background=”@drawable/download1″
android:layout_marginTop=”15dp”/>

<Button android:id=”@+id/Button03″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:background=”@drawable/images”
android:layout_marginTop=”15dp”/>

</LinearLayout>

</SlidingDrawer>

</RelativeLayout>

 

Java file: 

package com.CoreProgrammers.drawer;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.Toast;

public class slidingDrawerExample extends Activity
{

Button slideHandleButton;
SlidingDrawer slidingDrawer;
Button Button01;
Button Button02;
Button Button03;

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

slideHandleButton = (Button) findViewById(R.id.slideHandleButton);
Button01= (Button) findViewById(R.id.Button01);
Button02= (Button) findViewById(R.id.Button02);
Button03= (Button) findViewById(R.id.Button03);

slidingDrawer = (SlidingDrawer) findViewById(R.id.SlidingDrawer);

slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener()
{
@Override
public void onDrawerOpened()
{
slideHandleButton.setBackgroundResource(R.drawable.openarrow);
}
});

slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener()
{

@Override
public void onDrawerClosed()
{
slideHandleButton.setBackgroundResource(R.drawable.closearrow);
}

});

Button01.setOnClickListener(new OnClickListener()
{

@Override
public void onClick(View v)
{

Toast toast = Toast.makeText(slidingDrawerExample.this, “Facebook!!”, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.LEFT, 0 , 0);
toast.show();
}
});

Button02.setOnClickListener(new OnClickListener()
{

@Override
public void onClick(View v)
{
Toast toast = Toast.makeText(slidingDrawerExample.this, “Whatsapp!!”, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.LEFT, 0 , 0);
toast.show();
}
});

Button03.setOnClickListener(new OnClickListener()
{

@Override
public void onClick(View v)
{
Toast toast = Toast.makeText(slidingDrawerExample.this, “linkedin!!”, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.LEFT, 0 , 0);
toast.show();
}
});

}

}

ImageView in Android UI controls

ImageView is one of the UI Widgets that is used to display images in our Android Application. ImageView comes with different configuration options to support different scale types. Scale types options are used for scaling the bounds/boundary of an image to the bounds/boundary of current view.

below are the listed scale type configuration property of current view:

1) center
2) centerCrop
3) centerInside
4) fitCenter
5) fitEnd
6) fitStart
7) fitXY
8) matrix

imageview

.xml file:

java file:

package com.example.imageview;

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

public class MainActivity extends Activity
{
ImageView _objimageView;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//setting image resource from drawable
_objimageView = (ImageView) findViewById(R.id.imageView2);

}

}

DatePicker in Android UI controls

DatePicker is an Android UI Control which allows the user to select the date consisting of day, month and year in any custom user interface, to achieve this functionality Android Provides DatePicker dialog components/class.

Important Methods of the DatePicker control:

1) getDayOfMonth() :- This method of DatePicker control returns the selected day of month.

2) getMonth() :- This method of DatePicker control returns the selected month.

3) getYear() :- This method of DatePicker control returns the selected year.

4) setMaxDate(long maxDate) :- This method of DatePicker control, sets the maximum date supported by the DatePicker control in milliseconds started from January 1, 1997 00:00:00 .

5) setMinDate(long minDate) :- This method of DatePicker control, sets the minimum date supported by the DatePicker control in milliseconds started from january 1 , 1997 00:00:00 .

6) setSpinnerShown(boolean shown) :- This method of DatePicker control, sets the spinner of the DatePicker controlto true or false.

7) updateDate(int year, int month, int dayOfMonth) :- This method of DatePicker class is a very Important method which sets the date in the DatePicker control provided by the user or the developer.

DatePicker

.xml file:


java file:

package com.example.androiddatepicker;

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.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;

public class MainActivity extends Activity
{
private ImageButton imageButton;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText editText;

private DatePickerDialog.OnDateSetListener datePickerListener;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

imageButton = (ImageButton) findViewById(R.id.imageButton);

cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);

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

imageButton.setOnClickListener(new OnClickListener()
{
@SuppressWarnings(“deprecation”)
@Override

public void onClick(View v)
{
showDialog(0);
}
});

datePickerListener = new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
{
editText.setText(selectedDay + “-” + (selectedMonth + 1) + “-” + selectedYear);
}
};

}

@Override
@Deprecated
protected Dialog onCreateDialog(int i)
{
DatePickerDialog _objDatePickerDialog;

_objDatePickerDialog=new DatePickerDialog(MainActivity.this, datePickerListener, year, month, day);

return _objDatePickerDialog;
}

}

Progress Bar In Android UI Control

Progress  bar is used to show progress of a task.

for example when we are uploading or downloading something from internet, it is better to show the progress of download/upload to the. In Android there is a class call progress dialog that allows you to create a progress bar in order to do this we have to instantiate an object of this class.

device-2015-01-05-215451

 

 

 

 

Syntax is: progressdialog progress= new progressdialog(activity.this);

 

.xml file:

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

<ProgressBar android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="20dp"
android:indeterminate="false"
android:max="100"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1" />

<TextView android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/progressBar1"
android:layout_below="@+id/progressBar1"/>

</RelativeLayout>

java file:

package com.coreprogrammers.androidprogressbardemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity 
{
private ProgressBar progressBar;
private int progressStatus = 0;
private TextView textView;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

progressBar = (ProgressBar) findViewById(R.id.progressBar1);

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

// Start long running operation in a background thread
new Thread(new Runnable() 
{
public void run() 
{
while (progressStatus < 100) 
{

progressStatus += 1;
//progressStatus=progressStatus+1;
// Update the progress bar and display the 



try 
{
// code runs in a thread
runOnUiThread(new Runnable() 
{
@Override
public void run() 
{
progressBar.setProgress(progressStatus);
textView.setText(progressStatus+"/"+progressBar.getMax());
}
});
}
catch (final Exception ex)
{
Log.i("---","Exception in thread");
}


try 
{
//Sleep for 200 milliseconds. 
//Just to display the progress slowly
Thread.sleep(200);
} 
catch (InterruptedException e) 
{
e.printStackTrace();
}

}
}


}).start();

}



}

 

List of screen resolutions for all Android based phones and tablets

These are the sizes. Try to take a look in Supporting Mutiple Screens

320dp: a typical phone screen (240×320 ldpi,320×480 mdpi,480×800 hdpi, etc).480dp: a tweener tablet like the Streak(480×800 mdpi).600dp: a 7” tablet (600×1024 mdpi).720dp: a 10” tablet (720×1280 mdpi,800×1280 mdpi, etc).

Some times developers use this to make more than one layout:
res/layout/main_activity.xml # For handsets (smaller than 600dp available width)
res
/layoutsw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger)
res
/layoutsw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger)

 

The success of Android as a mobile device Operating System (OS) has resulted in a large variety of screen sizes and resolutions. Here is provided a list of example devices to show that variation.

 

phoneportraitvlandscape

In the following table we try to show each and every  resolution for Android Devices . As such the width in pixels is the X-axis and the length or height in pixels is the Y-axis. Obviously that swaps when the device is held in landscape orientation. Android has support for both orientations so that a correctly programmed App will work no matter which way you hold the device.  The total number of pixels in a screen is the number in the x-axis multiplied by the number in the y-axis. The more pixels for each square inch (or centimetre) of display the sharper any images will be displayed (provided those images are at a high resolution).

The Size column next to each device is the diagonal measurement for the device screen in inches. This table illustrates that screens with the same resolution can be different sizes.

 

Device Inches ResolutionPX Density OR Acronym DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
Galaxy Y 320 x 240 ldpi   0.75 120 427 x 320 4:3   1.3333 427 x 320
? 400 x 240 ldpi   0.75 120 533 x 320 5:3   1.6667 533 x 320
? 432 x 240 ldpi   0.75 120 576 x 320 9:5   1.8000 576 x 320
Galaxy Ace 480 x 320 mdpi   1 160 480 x 320 3:2   1.5000 480 x 320
Nexus S 800 x 480 hdpi   1.5 240 533 x 320 5:3   1.6667 533 x 320
“Galaxy SIII Mini” 800 x 480 hdpi   1.5 240 533 x 320 5:3   1.6667 533 x 320
? 854 x 480 hdpi   1.5 240 569 x 320 427:240   1.7792 569 x 320
Galaxy SIII 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
Galaxy Nexus 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
HTC One X 4.7″ 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
Nexus 5 5″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 YES 592 x 360
Galaxy S4 5″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
HTC One 5″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
Galaxy Note III 5.7″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
HTC One Max 5.9″ 1920 x 1080 xxhdpi   3 480 640 x 360 16:9   1.7778 640 x 360
Galaxy Note II 5.6″ 1280 x 720 xhdpi   2 320 640 x 360 16:9   1.7778 640 x 360
Nexus 4 4.4″ 1200 x 768 xhdpi   2 320 600 x 384 25:16   1.5625 YES 552 x 384
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
? 800 x 480 mdpi   1 160 800 x 480 5:3   1.6667 800 x 480
? 854 x 480 mdpi   1 160 854 x 480 427:240   1.7792 854 x 480
Galaxy Mega 6.3″ 1280 x 720 hdpi   1.5 240 853 x 480 16:9   1.7778 853 x 480
Kindle Fire HD 7″ 1280 x 800 hdpi   1.5 240 853 x 533 8:5   1.6000 853 x 533
Galaxy Mega 5.8″ 960 x 540 tvdpi   1.33333 213.333 720 x 405 16:9   1.7778 720 x 405
Sony Xperia Z Ultra 6.4″ 1920 x 1080 xhdpi   2 320 960 x 540 16:9   1.7778 960 x 540
Kindle Fire (1st & 2nd gen) 7″ 1024 x 600 mdpi   1 160 1024 x 600 128:75   1.7067 1024 x 600
Tesco Hudl 7″ 1400 x 900 hdpi   1.5 240 933 x 600 14:9   1.5556 933 x 600
Nexus 7 (1st gen/2012) 7″ 1280 x 800 tvdpi   1.33333 213.333 960 x 600 8:5   1.6000 YES 912 x 600
Nexus 7 (2nd gen/2013) 7″ 1824 x 1200 xhdpi   2 320 912 x 600 38:25   1.5200 YES 864 x 600
Kindle Fire HDX 7″ 1920 x 1200 xhdpi   2 320 960 x 600 8:5   1.6000 960 x 600
? 800 x 480 ldpi   0.75 120 1067 x 640 5:3   1.6667 1067 x 640
? 854 x 480 ldpi   0.75 120 1139 x 640 427:240   1.7792 1139 x 640
Kindle Fire HD 8.9″ 1920 x 1200 hdpi   1.5 240 1280 x 800 8:5   1.6000 1280 x 800
Kindle Fire HDX 8.9″ 2560 x 1600 xhdpi   2 320 1280 x 800 8:5   1.6000 1280 x 800
Galaxy Tab 2 10″ 1280 x 800 mdpi   1 160 1280 x 800 8:5   1.6000 1280 x 800
Galaxy Tab 3 10″ 1280 x 800 mdpi   1 160 1280 x 800 8:5   1.6000 1280 x 800
ASUS Transformer 10″ 1280 x 800 mdpi   1 160 1280 x 800 8:5   1.6000 1280 x 800
ASUS Transformer 2 10″ 1920 x 1200 hdpi   1.5 240 1280 x 800 8:5   1.6000 1280 x 800
Nexus 10 10″ 2560 x 1600 xhdpi   2 320 1280 x 800 8:5   1.6000 1280 x 800
Galaxy Note 10.1 10″ 2560 x 1600 xhdpi   2 320 1280 x 800 8:5   1.6000 1280 x 800
Dell Aero 3.5″ 360 X 640 nHD   —
Motorola Pro+ MB632 3.1″ 480 X 640 VGA   —
——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ——————————— ———————————
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP

Design Layout For Multiple Android Screens

When we need to create different layout for different screen size. Support all screen we need to create following layout:

 

1) Low density Small screens QVGA 240×320 (120dpi):

layout-small-ldpi (240x320)  
layout-small-land-ldpi (320x240)

 

2) Low density Normal screens WVGA400 240×400 (x432) (120dpi):

layout-ldpi  (240 x 400 )
layout-land-ldpi  (400 x 240 )

 

3) Medium density Normal screens HVGA 320×480 (160dpi):

layout-mdpi (320 x 480 )
layout-land-mdpi (480 x 320 )

 

4) Medium density Large screens HVGA 320×480 (160dpi):

layout-large-mdpi (320 x 480 )
layout-large-land-mdpi (480 x 320)

 

5) Galaxy Tab ( 240 dpi ):

layout-large  (600 x 1024) 
layout-large-land  (1024 x 600)

 

6) High density Normal screens WVGA800 480×800 (x854) (240 dpi):

layout-hdpi (480 x 800)
layout-land-hdpi (800 x 480)

 

7) For Screen Size of 720×1280 (320 dpi):

layout-xhdpi (720 x 1280)
layout-land-xhdpi (1280 x 720)

 

8) Xoom (medium density large but 1280×800 res) (160 dpi):

layout-xlarge (800 x 1280)
layout-xlarge-land (1280 x 800)

 

 Also add following code in .manifest file:- 

<supports-screens                                 
    android:smallScreens="true"                    
    android:normalScreens="true"         
    android:largeScreens="true"            
    android:xlargeScreens="true"             
    android:anyDensity="true" />

 

Android Global Variables/Application Context Variable

In this example we are going to learn to define variables in application context and we can use this variables as a Global variable. We can set values in this variables  and get values on any activity / broadcast recieiver / service in application context(environment).

The challenge is how to save values across several Activities and all parts of your application context. We can achieve this by creating static variable but it is not a good way as it will causes memory leaks. The solution for this in Android is to associate your variable with the Application context.

Every Application has a context, and Android guarantees that Application context will exist as a instance across your application.

The way to do this is to create a class and extends with android.app.Application, and specify your class in the application tag in your AndroidManifest.xml file. Android will create an instance of that class and make it available for your entire application context. We can get object of our class on any activity / broadcast reciever / service in application context(environment) by Context.getApplicationContext() method.

Now lets create a project to understand variables under Application Context:-

Create a class named AuthenticationDetails.java and extent it with ‘Application’ our custom class should be subclass of android.app.Application class. We will use this class as global class for your Application environment(Conext).

AuthenticationDetails.java

package com.coreprogrammers.model;

import android.app.Application;

public class AuthenticationDetails extends Application
{
	private String id;
	private String name;
	private String company;
	private String username;
	private String password;
	private String s3_key;
	private String s3_secret;
	private String api_key;
	private String license;
	private String timezone;
	private String tied_to;
	private String app;
	private String paypal;
	private String cron;
	private String cron_ares;
	private String send_rate;
	private String language;
	private String cron_csv;
	private String login_in;

	public void setid(String strid) 
	{
		this.id = strid;
	}

	public String getid() 
	{
		return id;
	}

	public void setname(String strname) 
	{
		this.name = strname;
	}

	public String getname() 
	{
		return name;
	}

	public void setcompany(String strcompany) 
	{
		this.company = strcompany;
	}

	public String getcompany() 
	{
		return company;
	}

	public void setusername(String strusername) 
	{
		this.username = strusername;
	}

	public String getusername() 
	{
		return username;
	}

	public void setpassword(String strpassword) 
	{
		this.password = strpassword;
	}

	public String getpassword() 
	{
		return password;
	}

	public void sets3_key(String strs3_key) 
	{
		this.s3_key = strs3_key;
	}

	public String gets3_key() 
	{
		return s3_key;
	}

	public void sets3_secret(String strs3_secret) 
	{
		this.s3_secret = strs3_secret;
	}

	public String gets3_secret() 
	{
		return s3_secret;
	}

	public void setapi_key(String strapi_key) 
	{
		this.api_key = strapi_key;
	}

	public String getapi_key() 
	{
		return api_key;
	}

	public void setlicense(String strlicense) 
	{
		this.license = strlicense;
	}

	public String getlicense() 
	{
		return license;
	}

	public void settimezone(String strtimezone) 
	{
		this.timezone = strtimezone;
	}

	public String gettimezone() 
	{
		return timezone;
	}

	public void settied_to(String strtied_to) 
	{
		this.tied_to = strtied_to;
	}

	public String gettied_to() 
	{
		return tied_to;
	}

	public void setapp(String strapp) 
	{
		this.app = strapp;
	}

	public String getapp() 
	{
		return app;
	}

	public void setpaypal(String strpaypal) 
	{
		this.paypal = strpaypal;
	}

	public String getpaypal() 
	{
		return paypal;
	}

	public void setcron(String strcron) 
	{
		this.cron = strcron;
	}

	public String getcron() 
	{
		return cron;
	}

	public void setcron_ares(String strcron_ares) 
	{
		this.cron_ares = strcron_ares;
	}

	public String getcron_ares() 
	{
		return cron_ares;
	}

	public void setsend_rate(String strsend_rate) 
	{
		this.send_rate = strsend_rate;
	}

	public String getsend_rate() 
	{
		return send_rate;
	}

	public void setlanguage(String strlanguage) 
	{
		this.language = strlanguage;
	}

	public String getlanguage() 
	{
		return language;
	}

	public void setcron_csv(String strcron_csv) 
	{
		this.cron_csv = strcron_csv;
	}

	public String getcron_csv() 
	{
		return cron_csv;
	}

	public void setlogin_in(String strlogin_in) 
	{
		this.login_in = strlogin_in;
	}

	public String getlogin_in() 
	{
		return login_in;
	}	
}

 

Now We are going to create  AndroidManifest.xml.

In AndroidManifest file we will Assign AuthenticationDetails.java in application tag, see this line in application tag android:name=”com.coreprogrammers.model.AuthenticationDetails” . After assign we can get AuthenticationDetails.java instance on any activity / broadcast reciever / service in application context.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coreprogrammers.model"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />

    <application
        android:name="com.coreprogrammers.model.AuthenticationDetails"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.coreprogrammers.model.FirstScreen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity android:name="com.coreprogrammers.model.SecondScreen" ></activity>  
        <activity android:name="com.coreprogrammers.model.ThirdScreen" ></activity>
    </application>

</manifest>

Now we will show how to use the global variables across three activities

1) FirstScreen.java

getApplicationContext() method of Context will give AuthenticationDetails.java instance and set id/name values and maintain state of AuthenticationDetails.java instance.

package com.coreprogrammers.model;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;

public class FirstScreen extends Activity 
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstscreen);

        final Button secondBtn = (Button) findViewById(R.id.second);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        //Set name and id in global/application context
        _objAuthenticationDetails.setname("Coreprogrammers");
        _objAuthenticationDetails.setid("Rocks");

        secondBtn.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
                Intent i = new Intent(getBaseContext(), SecondScreen.class);
                startActivity(i);
            }
        }); 
    }   
}

 

2) SecondScreen.java

We have to Call getApplicationContext() method of Context and get AuthenticationDetails.java instance , By AuthenticationDetails.java instance we can get set values for name/id variables.

package com.coreprogrammers.model;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreen extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondscreen); 

        TextView showGlobal = (TextView) findViewById(R.id.showGlobal);
        final Button thirdBtn = (Button) findViewById(R.id.third);

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        // Get name and id from global/application context
        final String name  = _objAuthenticationDetails.getname();
        final String id = _objAuthenticationDetails.getid();

        String showString = "Name= : "+ name + "ID : "+ id;

        // Show name/email values in TextView
        showGlobal.setText(showString);

        thirdBtn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v) 
            {
                Intent i = new Intent(getBaseContext(), ThirdScreen.class);
                startActivity(i);
            }
        });

    } 

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
    }
}

 

3) ThirdScreen.java

Now we will call getApplicationContext() method of Context and get AuthenticationDetails.java instance , By AuthenticationDetails.java instance we can get and set values for name/id variables.

package com.coreprogrammers.model;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ThirdScreen extends Activity 
{

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thirdscreen); 

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

        // Calling Application class (see application tag in AndroidManifest.xml)
        final AuthenticationDetails _objAuthenticationDetails = (AuthenticationDetails) getApplicationContext();

        // Get name and email from global/application context
        final String name  = _objAuthenticationDetails.getname();
        final String id = _objAuthenticationDetails.getid();

        String showString = "Name= "+ name +" "+ "ID= "+ id;

        // Show name/id values in TextView
        showGlobal.setText(showString);

    } 
}

Happy Programming :-)

 

Android Fragments Part-3 (Adding a user interface)

A fragment is usually used as part of an activity’s user interface and contributes its own layout to the activity.

To provide a layout for a fragment, we must implement the onCreateView() callback method, which the Android system calls when it’s time for the fragment to draw its layout. Our implementation of this method must return a View  that is the root of our fragment’s layout.

Note: If the fragment is a subclass of ListFragment, the default implementation returns a ListView from onCreateView(), so we don’t need to implement it.

To return a layout from onCreateView(), we can inflate it from a layout resource defined in XML. To help you do so, onCreateView() provides a LayoutInflater object.

For example, here’s a subclass of Fragment that loads a layout from the fragment_example.xml file:-

public static class FragmentExample extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_example, container, false);
    }
}

How to Create a layout

In the sample above,R.layout.fragment_example is a reference to a layout resource named fragment_example.xml saved in the application resources.

Explanation:-

The container parameter passed to onCreateView() is the parent ViewGroup (from the activity’s layout) in which your fragment layout will be inserted. The savedInstanceState parameter is a Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed .

The inflate() method takes three arguments:

  • The resource ID of the layout you want to inflate.
  • The ViewGroup to be the parent of the inflated layout. Passing the container is important in order for the system to apply layout parameters to the root view of the inflated layout, specified by the parent view in which it’s going.
  • A boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during inflation. (In this case, this is false because the system is already inserting the inflated layout into the container—passing true would create a redundant view group in the final layout.)

Now we’ve seen how to create a fragment that provides a layout. Next, we now need to add the fragment to our activity. We will learn to add the fragment to the activity in our next Tutorial  Android Fragments Part-4

Android Fragments Part-2 (Types Of Fragments)

There are some few subclasses that you might want to extend, instead of the base Fragment class:

DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment.
ListFragment
Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events.
PreferenceFragment
Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a “settings” activity for your application.

Skip to toolbar