页面布局content_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= "match_parent"
android :layout_height= "match_parent"
>
<!--定义一个ImageView组件-->
<ImageView
android :id= "@+id/imageView"
android :layout_width= "320dp"
android :layout_height= "320dp"
/>
<!--定义一个Gallery组件-->
<!-- android:unselectedAlpha="0.6" 为没有选中的图片的透明度 -->
<Gallery
android :id= "@+id/gallery"
android :layout_width= "match_parent"
android :layout_height= "wrap_content"
android :layout_marginTop= "25dp"
android :unselectedAlpha= "0.6"
android :spacing= "2pt"
/>
</<span style="font-family: Arial, Helvetica, sans-serif;">LinearLayout</span><span style="font-family: Arial, Helvetica, sans-serif;">></span>
用BaseAdapter将图片显示在布局上
package com.eson.gallery ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.view.ViewGroup ;
import android.widget.AdapterView ;
import android.widget.BaseAdapter ;
import android.widget.Gallery ;
import android.widget.ImageView ;
public class GalleryTest extends AppCompatActivity {
int [] imageIds= new int []{
R.drawable. img1, R.drawable. img2, R.drawable. img3, R.drawable. img4,
R.drawable. img5 ,R.drawable. img6 ,R.drawable. img7 ,R.drawable. img8 ,
R.drawable. img9 ,R.drawable. img10 ,R.drawable. img11 ,R.drawable. img12 ,
} ;
private Gallery gallery ;
private ImageView imageView ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main );
gallery = (Gallery) findViewById(R.id. gallery );
//获取显示图片的ImageView对象
imageView = (ImageView) findViewById(R.id. imageView );
BaseAdapter adapter= new BaseAdapter() {
@Override
public int getCount () {
return imageIds . length;
}
@Override
public Object getItem( int position) {
return position ;
}
@Override
public long getItemId (int position) {
return position ;
}
//该方法返回View代表了每个列表项
@Override
public View getView( int position, View convertView , ViewGroup parent) {
//创建一个ImageView
ImageView imageView = new ImageView(GalleryTest. this) ;
imageView.setImageResource( imageIds[position]) ;
//设置ImageView设置布局参数
imageView.setLayoutParams( new Gallery.LayoutParams( 150 , 200 )) ;
return imageView;
}
};
gallery .setAdapter(adapter) ;
gallery .setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
//当Gallery选项发生改变时触发该方法
@Override
public void onItemSelected (AdapterView<?> parent , View view , int position, long id) {
imageView.setImageResource( imageIds [position]);
}
@Override
public void onNothingSelected (AdapterView<?> parent) {
}
});
}
}