Example
program
ImageAdapter
package
com.ipsr.gallerydemo;
import
android.content.Context;
import
android.view.View;
import
android.view.ViewGroup;
import
android.widget.BaseAdapter;
import
android.widget.Gallery;
import
android.widget.ImageView;
public
class ImageAdapter extends BaseAdapter {
/**
The parent context */
private
Context myContext;
/**
All images to be displayed.
*
Put some images to project-folder:
*
'/res/drawable/uvw.xyz' .*/
private
int[] myImageIds = {
R.drawable.helpsh,
R.drawable.icon,
R.drawable.logout,
R.drawable.phoneicons
};
/**
Simple Constructor saving the 'parent' context. */
public
ImageAdapter(Context c) { this.myContext = c; }
/**
Returns the amount of images we have defined. */
public
int getCount() { return this.myImageIds.length; }
/*
Use the array-Positions as unique IDs */
public
Object getItem(int position) { return position; }
public
long getItemId(int position) { return position; }
/**
Returns a new ImageView to
*
be displayed, depending on
*
the position passed. */@Override
public
View getView(int position, View convertView, ViewGroup parent) {
ImageView
i = new ImageView(this.myContext);
i.setImageResource(this.myImageIds[position]);
/*
Image should be scaled as width/height are set. */
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
/*
Set the Width/Height of the ImageView. */
i.setLayoutParams(new
Gallery.LayoutParams(150, 150));
return
i;
}
/**
Returns the size (0.0f to 1.0f) of the views
*
depending on the 'offset' to the center. */
public
float getScale(boolean focused, int offset) {
/*
Formula: 1 / (2 ^ offset) */
return
Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}
GalleryExampleActivity
package
com.ipsr.gallerydemo;
import
android.app.Activity;
import
android.os.Bundle;
import
android.widget.Gallery;
public
class
GalleryExampleActivity extends
Activity {
/**
Called when the activity is first created. */
@Override
public
void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g=(Gallery)
findViewById(R.id.gallery1);
g.setAdapter(new
ImageAdapter(this));
}
}
Multimedia and Camera
The Android multimedia framework includes support for capturing and playing audio, video and images in a variety of common media types, so that you can easily integrate them into your applications. You can play audio or video from media files stored in your application's resources, from standalone files in the file system, or from a data stream arriving over a network connection, all using theMediaPlayer
or JetPlayer
APIs. You can also record audio, video and take pictures using the
MediaRecorder
and Camera
APIs if supported by the device hardware.The following topics show you how to use the Android framework to implement multimedia capture and playback.
- Media Playback
- How to play audio and video in your application.
- JetPlayer
- How to play interactive audio and video in your application using content created with JetCreator.
- Camera
- How to use a device camera to take pictures or video in your application.
- Audio Capture
- How to record sound in your application.
Popup
Tabs and TabActivity
Popup
Tabs
In
Android you can display pop up messages that lasts for a certain
duration and then disappears-using the Toast
class.
Toast is a transient message that appears and disappears without any interaction from the user and with no notification to the program that it disappeared.
the Toast can display a simple text message or a complex view.
Displaying simple text:
to display a simple toast that displays a text message we use the following code:
Toast is a transient message that appears and disappears without any interaction from the user and with no notification to the program that it disappeared.
the Toast can display a simple text message or a complex view.
Displaying simple text:
to display a simple toast that displays a text message we use the following code:
1 |
Toast toast=Toast.makeText(this, "Hello
toast", 2000); |
2 |
toast.setGravity(Gravity.TOP,
-30, 50); |
3 |
toast.show(); |
we create the toast using the static Toast.makeText(Context con,String message, int duration) method to create a toast in the current context to display a text message for a duration specified in milli seconds or we can use the constant values Toast.LENGTH_SHORT to display for a short duration or Toast.LENGTH_LONG for longer duration.
The toast by default appears in the center of the screen, you can change the default position by specifying the Gravity and the X and Y offsets.
finally we call the Show() method to display the toast.
the previous toast will be like this:
Displaying complex views:
Toasts can also display complex views. this is done like this:
First: create a layout xml file in res/layout directory. the file must be named toast_layout.xml.
01 |
<?xml version="1.0"
encoding="utf-8"?> |
02 |
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" |
03 |
android:orientation="vertical" |
04 |
android:layout_width="fill_parent" |
05 |
android:layout_height="fill_parent" |
06 |
android:id="@+id/toastView" |
07 |
> |
08 |
<TextView |
09 |
android:layout_width="fill_parent" |
10 |
android:layout_height="wrap_content" |
11 |
android:text="Hello
toast" |
12 |
android:textColor="#000" |
13 |
/> |
14 |
<TextView |
15 |
android:layout_width="fill_parent" |
16 |
android:layout_height="wrap_content" |
17 |
android:id="@+id/txtDate" |
18 |
android:textColor="#000" |
19 |
/> |
20 |
|
21 |
|
22 |
</LinearLayout> |
then from the code
1 |
Toast toast=new Toast(this); |
2 |
LayoutInflater
inflater=this.getLayoutInflater(); |
3 |
View
toastView=inflater.inflate(R.layout.toast_layout,
(ViewGroup)findViewById(R.id.toastView)); |
4 |
TextView
txtDate=(TextView)toastView.findViewById(R.id.txtDate); |
5 |
txtDate.setText("toast
appeared at "+Calendar.getInstance().getTime().toLocaleString()); |
6 |
toast.setGravity(Gravity.CENTER,
0, 0); |
7 |
toast.setView(toastView); |
8 |
toast.show(); |
the toast will be like this:
Notes:
- In the toast_layout.xml width, if you put any buttons or any control that has a callback, it would appear disabled and the user cannot interact with it.
- The toast can be created in two ways: by calling
Toast.makeText method or by specifyinga view via
setView method. when you want to display a simple
text use the first one otherwise use the second. if you try to
interchange or combie between the two methods an exception will
be thrown
TabActivity
For apps developing against
HONEYCOMB
or later, tabs are typically presented in the UI using the new
ActionBar.newTab()
and related APIs for placing tabs within their action bar area.A replacement for TabActivity can also be implemented by directly using TabHost. You will need to define a layout that correctly uses a TabHost with a TabWidget as well as an area in which to display your tab content. A typical example would be:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0"/> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0"/> <FrameLayout android:id="@+android:id/realtabcontent" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout> </TabHost>The implementation needs to take over responsibility for switching the shown content when the user switches between tabs.
import java.util.HashMap; import com.example.android.supportv4.R; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.TabHost; /** * This demonstrates how you can implement switching between the tabs of a * TabHost through fragments. It uses a trick (see the code below) to allow * the tabs to switch between fragments instead of simple views. */ public class FragmentTabs extends FragmentActivity { TabHost mTabHost; TabManager mTabManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_tabs); mTabHost = (TabHost)findViewById(android.R.id.tabhost); mTabHost.setup(); mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent); mTabManager.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"), FragmentStackSupport.CountingFragment.class, null); mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"), LoaderCursorSupport.CursorLoaderListFragment.class, null); mTabManager.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"), LoaderCustomSupport.AppListFragment.class, null); mTabManager.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"), LoaderThrottleSupport.ThrottledLoaderListFragment.class, null); if (savedInstanceState != null) { mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("tab", mTabHost.getCurrentTabTag()); } /** * This is a helper class that implements a generic mechanism for * associating fragments with the tabs in a tab host. It relies on a * trick. Normally a tab host has a simple API for supplying a View or * Intent that each tab will show. This is not sufficient for switching * between fragments. So instead we make the content part of the tab host * 0dp high (it is not shown) and the TabManager supplies its own dummy * view to show as the tab content. It listens to changes in tabs, and takes * care of switch to the correct fragment shown in a separate content area * whenever the selected tab changes. */ public static class TabManager implements TabHost.OnTabChangeListener { private final FragmentActivity mActivity; private final TabHost mTabHost; private final int mContainerId; private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>(); TabInfo mLastTab; static final class TabInfo { private final String tag; private final Class<?> clss; private final Bundle args; private Fragment fragment; TabInfo(String _tag, Class<?> _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) { mActivity = activity; mTabHost = tabHost; mContainerId = containerId; mTabHost.setOnTabChangedListener(this); } public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) { tabSpec.setContent(new DummyTabFactory(mActivity)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, clss, args); // Check to see if we already have a fragment for this tab, probably // from a previously saved state. If so, deactivate it, because our // initial state is that a tab isn't shown. info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag); if (info.fragment != null && !info.fragment.isDetached()) { FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction(); ft.detach(info.fragment); ft.commit(); } mTabs.put(tag, info); mTabHost.addTab(tabSpec); } @Override public void onTabChanged(String tabId) { TabInfo newTab = mTabs.get(tabId); if (mLastTab != newTab) { FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction(); if (mLastTab != null) { if (mLastTab.fragment != null) { ft.detach(mLastTab.fragment); } } if (newTab != null) { if (newTab.fragment == null) { newTab.fragment = Fragment.instantiate(mActivity, newTab.clss.getName(), newTab.args); ft.add(mContainerId, newTab.fragment, newTab.tag); } else { ft.attach(newTab.fragment); } } mLastTab = newTab; ft.commit(); mActivity.getSupportFragmentManager().executePendingTransactions(); } } } }
Public Constructors
public TabActivity ()
Since: API Level 1Public Methods
public TabHost getTabHost ()
Since: API Level 1Returns the
TabHost
the activity is using to host its tabs.Returns
- the
TabHost
the activity is using to host its tabs.
public TabWidget getTabWidget ()
Since: API Level 1Returns the
TabWidget
the activity is using to draw the actual tabs.Returns
- the
TabWidget
the activity is using to draw the actual tabs.
public void onContentChanged ()
Since: API Level 1Updates the screen state (current list and other views) when the content changes.
See Also
public void setDefaultTab (String tag)
Since: API Level 1Sets the default tab that is the first tab highlighted.
Parameters
tag
|
the name of the default tab
|
---|
public void setDefaultTab (int index)
Since: API Level 1Sets the default tab that is the first tab highlighted.
Parameters
index
|
the index of the default tab
|
---|
Protected Methods
protected void onChildTitleChanged (Activity childActivity, CharSequence title)
Since: API Level 1protected void onPostCreate (Bundle icicle)
Since: API Level 1Called when activity start-up is complete (after
onStart()
and onRestoreInstanceState(Bundle)
have been called). Applications will generally not implement this
method; it is intended for system classes to do final initialization
after application code has run.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
Parameters
icicle
|
If the activity is being re-initialized after previously being
shut down then this Bundle contains the data it most recently
supplied in onSaveInstanceState(Bundle) .
Note: Otherwise it is null. |
---|
protected void onRestoreInstanceState (Bundle state)
Since: API Level 1This method is called after
onStart()
when the activity is being re-initialized from a previously saved
state, given here in savedInstanceState. Most
implementations will simply use onCreate(Bundle)
to restore their state, but it is sometimes convenient to do it here
after all of the initialization has been done or to allow subclasses
to decide whether to use your default implementation. The default
implementation of this method performs a restore of any view state
that had previously been frozen by onSaveInstanceState(Bundle)
.
This method is called between
onStart()
and onPostCreate(Bundle)
.Parameters
state
|
the data most recently supplied in onSaveInstanceState(Bundle) . |
---|
protected void onSaveInstanceState (Bundle outState)
Since: API Level 1Called to retrieve per-instance state from an activity before being killed so that the state can be restored in
onCreate(Bundle)
or onRestoreInstanceState(Bundle)
(the Bundle
populated by this method will be passed to both).
This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via
onCreate(Bundle)
or onRestoreInstanceState(Bundle)
.
Do not confuse this method with activity lifecycle callbacks such as
onPause()
,
which is always called when an activity is being placed in the
background or on its way to destruction, or onStop()
which is called before destruction. One example of when onPause()
and onStop()
is called and not this method is when a user navigates back from
activity B to activity A: there is no need to call
onSaveInstanceState(Bundle)
on B because that particular instance will never be restored, so the
system avoids calling it. An example when onPause()
is called and not onSaveInstanceState(Bundle)
is when activity B is launched in front of activity A: the system may
avoid calling onSaveInstanceState(Bundle)
on activity A if it isn't killed during the lifetime of B since the
state of the user interface of A will stay intact.
The default implementation takes care of most of the UI per-instance state for you by calling
onSaveInstanceState()
on each view in the hierarchy that has an id, and by saving the id of
the currently focused view (all of which is restored by the default
implementation of onRestoreInstanceState(Bundle)
).
If you override this method to save additional information not
captured by each individual view, you will likely want to call
through to the default implementation, otherwise be prepared to save
all of the state of each view yourself.
If called, this method will occur before
onStop()
.
There are no guarantees about whether it will occur before or after
onPause()
.Parameters
outState
|
Bundle in which to place your saved state. |
---|
No comments:
Post a Comment