Android generates user interfaces either from XML or from Java code.
Views
Creating and adding a new View to a Layout in XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/mainLayout" >
<TextView
android:text="My text view"
android:id="@+id/TextViewExample"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>
View Groups
A ViewGroupis a special view that can contain other views.
List view
ListView list = new ListView(this);
String[] listItems = {"Option 1","Option 2","Option 3"};
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems ));
list.setOnItemClickListener(new OnItemClickListener() {...
Layouts
A Layout is a type of GroupView. It holds views in a certain layout on the screen.
Adding a Layout - XML example - adding to the layout XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:id="@+id/outer"
android:orientation="vertical">
</LinearLayout>
The layout xml is placed in <project_path>/res/layouts
Adding a Layout - Code example
This would be implemented in an Activity class.
LinearLayout innerLayout = new LinearLayout(this);
innerLayout.setPadding(20,20,20,20);
innerLayout.setGravity(Gravity.CENTER);
outerLayout.addView(innerLayout );
Global Strings
A global string, or an array of strings, are declared in an external xml file in the resource folder:<project>/res/values/strings.xml
Declaring a global string
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World!</string>
<string name="app_name">MyTest</string>
</resources>
Using a global string while creating a TextView
TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
Code usage
String hello = context.getString(R.string.hello);
Global String Array
Declaration in a Global String Array
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
</resources>
Code usage
String[] planets = context.getResources().getStringArray(R.array.planets_array);
Menus
Options Menu
An Options menu is presented when the user presses the menu button while the Activity is active.
Step 1 - Creating the menu XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game" />
<item android:id="@+id/quit"
android:icon="@drawable/ic_quit"
android:title="@string/quit" />
</menu>
The layout xml is placed in <project_path>/res/menu
Step 2 – Displaying the menu (implemented in Activity class)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
Step 3 – Listening to user choice (implemented in Activity class)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.quit:
quit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Context Menu
A context menu is a floating list of menu items that appears when the user performs a long-press on a View.
Step 1 - Creating a menu XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game" />
<item android:id="@+id/quit"
android:icon="@drawable/ic_quit"
android:title="@string/quit" />
</menu>
Step 2 – Showing the menu (implemented in Activity class)
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
Step 3 – Listening to user choice (implemented in Activity class)
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
editNote(info.id);
return true;
case R.id.delete:
deleteNote(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
Step 4 – Attaching the context menu to a view (implemented in Activity class)
registerForContextMenu(findViewById(R.id.Button01));
Submenu
A submenu is a floating list of menu items that the user opens by pressing a menu item in the Options Menu or a context menu.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/file"
android:icon="@drawable/file"
android:title="@string/file" >
<!-- "file" submenu -->
<menu>
<item android:id="@+id/new"
android:title="@string/new" />
<item android:id="@+id/open"
android:title="@string/open" />
</menu>
</item>
</menu>
Alerts/Dialogs
Toast
A toast notification is a message that pops up on the surface of the window.
Toast waitToast = Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG);
waitToast.setGravity(Gravity.TOP, 0, 0);
waitToast.show();
AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
Status-Bar Notifications
One way to notify an Android user is by displaying notifications in the status bar. You can show a message, play a sound, add an icon and more.
Creating a status bar notification
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Notification Test", System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence contentTitle = "My notification Title";
CharSequence contentText = "This is the message";
Intent notificationIntent = new Intent(NotificationTest.this, NotificationTest.class);
//options
notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "4"); //sound
notification.vibrate = new long[]{0,100,200,300}; //vibrate
//auto cancel after select
notification.flags |= Notification.FLAG_AUTO_CANCEL;
PendingIntent contentIntent = PendingIntent.getActivity(NotificationTest.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
Resource Images
Resource images are placed under <project_dir>/res/drawable
Using a resource image in an image view - XML example
((ImageView)findViewById(R.id.myImageView)).setImageResource(R.drawable.my_image_name);
Turning the resource image to a Bitmap object
Bitmap bitmap = BitmapFactory.decodeResource(view.getResources(),R.drawable.my_image_name);
Drawing the bitmap on a canvas object
canvas.drawBitmap(bitmap, x, y, null);
Creating Links Using Linkfy
Linkfy is a class that lets you create links from TextViews.
You can create links not just to web sites, but to also map addresses, emails and even phone numbers.
Creating web links
>TextView myWebSite = (TextView) findViewById(R.id.my_web_site);
myWebSite.setText(http://http://www.dzone.com/)
Linkify.addLinks(myWebSite , Linkify.WEB_URLS);
You can also create links to phone numbers, map locations or email addresses.
Using a regular expressionfor filtering strings
TextView myCustomLink = new TextView(this);
Pattern pattern = Pattern.compile("[a-zA-Z]+&");
myCustomLink.setText("press Linkify& or on Android& to search it on google");
Linkify.addLinks(myCustomLink,pattern, "http://www.google.ie/search?q=");
mainLayout.addView(myCustomLink);
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}