你曾經被iphone用手指在螢幕劃來花去拖動相片吸引嗎?在Android同樣能夠實現,而且不是什麼難事。
這裡需要用到android.content.Context;android.widget.BaseAdapter;android.wiget.ImageView;等。
android.content.Context在Activity中類似於一張Canvas畫布,能夠隨時處理或覆蓋它。Context與Intent一樣是android.content的子類。
本執行個體通過在layout中放置Gallery對象,然後通過android.widget.BaseAdapter容器放置Gallery所需要的圖片,本案例使用系統預設的ICON圖片。
1.,拖拽Gallery控制項到layout中,ID設定為myGallery1
查看res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Gallery android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/myGallery1"></Gallery></LinearLayout>
src/EX03_15.java
package gphone.ex03_15;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.Gallery;import android.widget.ImageView;public class EX03_15 extends Activity {private Gallery myGallery1=null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myGallery1=(Gallery)findViewById(R.id.myGallery1); myGallery1.setAdapter(new ImageAdapter(this)); } public class ImageAdapter extends BaseAdapter{ private Context myContext; //使用android.R.drawable裡系統預設圖片作為圖片源 private int[] myImageIds={ android.R.drawable.btn_minus, android.R.drawable.btn_radio, android.R.drawable.ic_lock_idle_low_battery, android.R.drawable.ic_menu_camera, android.R.drawable.btn_minus, android.R.drawable.btn_radio, android.R.drawable.ic_lock_idle_low_battery, android.R.drawable.ic_menu_camera,android.R.drawable.btn_minus, android.R.drawable.btn_radio, android.R.drawable.ic_lock_idle_low_battery, android.R.drawable.ic_menu_camera }; public ImageAdapter(Context c){ this.myContext=c; } @Override public int getCount() { // TODO Auto-generated method stub return this.myImageIds.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 建立ImageView ImageView i=new ImageView(this.myContext); i.setImageResource(this.myImageIds[position]); i.setScaleType(ImageView.ScaleType.FIT_XY); //設定ImageView對象的寬高,單位為dip i.setLayoutParams(new Gallery.LayoutParams(120, 120)); return i; } //根據中心點位移量 利用getScale返回views的大小(0.0f-1.0f) public float getScale(boolean focused,int offset){ return Math.max(0,1.0f/(float)Math.pow(2,Math.abs(offset))); } }}
運行效果