Android控件之Gallery(画廊)

 
 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <Gallery
            android:id="@+id/gallery1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:spacing="3pt"
            android:unselectedAlpha="0.6"
            android:layout_marginTop="25dp" />

    </LinearLayout>
 
 
 
 
package com.xplus.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		final int[] imageIds = new int[] { R.drawable.p1, R.drawable.p2,
				R.drawable.p3, R.drawable.p4, R.drawable.p5, R.drawable.p6,
				R.drawable.p7, R.drawable.p8, R.drawable.p9, R.drawable.p10,
				R.drawable.p11, R.drawable.p12 };

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		final Gallery gallery = (Gallery) findViewById(R.id.gallery1);
		final TextView text = (TextView) findViewById(R.id.textView1);

		BaseAdapter adapter = new BaseAdapter() {

			public View getView(int arg0, View arg1, ViewGroup arg2) {
				ImageView imageview = new ImageView(MainActivity.this);
				imageview.setImageResource(imageIds[arg0 % imageIds.length]);

				// 设置imageview的缩放类型
				imageview.setScaleType(ImageView.ScaleType.FIT_XY);
				imageview.setLayoutParams(new Gallery.LayoutParams(75, 100));
				return imageview;
			}

			public long getItemId(int arg0) {
				// TODO Auto-generated method stub
				return arg0;
			}

			public Object getItem(int arg0) {
				// TODO Auto-generated method stub
				return arg0;
			}

			public int getCount() {
				// TODO Auto-generated method stub
				return imageIds.length;
			}
		};
		gallery.setAdapter(adapter);
		// 设置选中图片时触发方法
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				text.setText("你选中的是:" + arg2);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				text.setText("你什么都没选中");
			}
		});

	}

}
主要是再xml中定义之后,在Activity中绑定适配器。

你可能感兴趣的:(android,xml,object,layout,Class)