Gallery控件与Adapter的应用

来源:互联网 发布:android软件开发工具包 编辑:程序博客网 时间:2024/06/08 11:44

        如何实现手机上相册里面的画廊效果,或者是查看图片的轮播效果,现在就讲一下如何实现。

        效果图:


        

Activity部分:

<span style="font-size:14px;">public class GalleryActivity extends Activity {ImageView iv = null;Gallery gallery = null;int[] drawId = {R.drawable.hongloumeng,R.drawable.sanguoyanyi,R.drawable.shuihuzhuan,R.drawable.xiyouji};@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.gallery_layout);iv = (ImageView)findViewById(R.id.image);gallery = (Gallery)findViewById(R.id.gallery);gallery.setAdapter(new MyBase());//通过点击事件来更换上面图片。注:区分listview的监听事件gallery.<strong>setOnItemSelectedListener</strong>(new OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent, View view,int position, long id) {iv.setImageDrawable(getResources().getDrawable(drawId[position]));}@Overridepublic void onNothingSelected(AdapterView<?> parent) {// TODO Auto-generated method stub}});}class MyBase extends BaseAdapter{@Overridepublic int getCount() {// TODO Auto-generated method stubreturn drawId.length;}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn null;}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stub                                //加载布局LayoutInflater flater = getLayoutInflater();View view = flater.inflate(R.layout.gallery_layout_1, null);ImageView iv = (ImageView)view.findViewById(R.id.innerImage);        iv.setImageDrawable(getResources().getDrawable(drawId[position]));return view;}}}</span>

layout文件

a、gallery_layout.xml

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >       <ImageView     android:id="@+id/image"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_weight="1"        //是图片所占的位置确定,不根据图片大小改变        />    <Gallery     android:id="@+id/gallery"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:spacing="10dp"                /></LinearLayout></span>
b、gallery_layout_1.xml

<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >      <ImageView         android:id="@+id/innerImage"        android:layout_width="match_parent"        android:layout_height="match_parent"        /></LinearLayout></span>
附上源码:

http://download.csdn.net/detail/chris_pei/9223027

0 0