Android常用高级组件之画廊控件使用

1.首先新建项目;

2.将所用要用到的资源文件存放在res/drawable-mdpi目录下;

3.编写布局文件main.xml,如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:spacing="10dip"
        android:unselectedAlpha="1"/>
LinearLayout>

4.开发主逻辑代码,如下:

package com.example.sample_5_8;

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

public class Sample_5_8 extends Activity 
{
    int[] imageIDs = {
        R.drawable.bbta, R.drawable.bbtb, R.drawable.bbtc,
        R.drawable.bbtd, R.drawable.bbte, R.drawable.bbtf,
        R.drawable.bbtg
    };

    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Gallery gl = (Gallery)this.findViewById(R.id.Gallery01);
        BaseAdapter ba = new BaseAdapter()
        {
            public View getView(int position, View convertView, ViewGroup parent)
            {
                ImageView iv = new ImageView(Sample_5_8.this);//初始化ImageView
                iv.setImageResource(imageIDs[position]);//设置图片资源
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                iv.setLayoutParams(new Gallery.LayoutParams(188, 250));
                return iv;
            }
            public long getItemId(int position)
            {
                return 0;
            }
            public Object getItem(int position)
            {
                return null;
            }
            public int getCount()
            {
                return imageIDs.length;
            }
        };
        gl.setAdapter(ba);
        gl.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView arg0, View arg1, int arg2,
                    long arg3)
            {
                Gallery gl = (Gallery)findViewById(R.id.Gallery01);
                gl.setSelection(arg2);//设置选中项
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    
}

5.程序运行结果如下:

Android常用高级组件之画廊控件使用_第1张图片

 

 

转载于:https://www.cnblogs.com/yujiaqiang/archive/2012/09/19/2694276.html

你可能感兴趣的:(Android常用高级组件之画廊控件使用)