Gallery画廊

GalleryAdapter.java:

package com.example.test10_gallery;

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 GalleryAdapter extends BaseAdapter {
    private Context mContext;
    //设置要展示的图片资源
    int[] images = {R.drawable.f1, R.drawable.f2, R.drawable.f3, R.drawable.f4};
    public GalleryAdapter(Context context) {
        this.mContext = context;
    }
    @Override
    public int getCount() {
        return images.length;
    }
    @Override
    public Object getItem(int i) {
        return i;
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        //在此最好判断一下view是否为空
        ImageView image = new ImageView(mContext);
        image.setImageResource(images[i]);
        image.setAdjustViewBounds(true);
        //设置宽高
        image.setLayoutParams(new Gallery.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        return image;
    }

}

MainActivity.java:

package com.example.test10_gallery;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.Toast;
public class MainActivity extends Activity {
GalleryAdapter galleryAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery);
galleryAdapter = new GalleryAdapter(MainActivity.this);
        gallery.setAdapter(galleryAdapter);
        //相应的点击事件
        gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, "您点击的是" + i, Toast.LENGTH_LONG).show();
            }
        });
}

}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >


    <Gallery
        android:id="@+id/gallery"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />


</RelativeLayout>


猜你喜欢

转载自blog.csdn.net/qq_42216503/article/details/80341396
今日推荐