Android:自定義適配器


無論是ArrayAdapter還是SimpleAdapter都繼承了BaseAdapter,自定義適配器同樣繼承BaseAdapter

實例:Gallery實現圖片瀏覽器

<?xml version="1.0" encoding="utf-8"?>
 <Gallery
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gallery"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    

</Gallery>

 

public class MainActivity extends Activity {
private Gallery gallery;
private int[] res={R.drawable.ic_launcher,R.drawable.ic_launcher};
private ImageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo);

        gallery = (Gallery) findViewById(R.id.gallery);
        
       adapter = new ImageAdapter(res, this);
        gallery.setAdapter(adapter);
        
        
        
    }


}

自定義的適配器

public class ImageAdapter  extends BaseAdapter{
    public int res[];
    private Context context;
    public ImageAdapter(int res[],Context context){
        this.res=res;
        this.context=context;
    }
    
    @Override
    //返回已定義數據源總數量
    public int getCount() {
        // TODO Auto-generated method stub
        return res.length;
    }

    @Override
    //告訴適配器取得目前容器中的數據對象
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    //告訴適配器取得目前容器中的數據ID
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    //取得當前欲顯示的圖像View
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ImageView image=new ImageView(context);
        image.setBackgroundResource(res[position]);
        image.setLayoutParams(new Gallery.LayoutParams(400,300));
        image.setScaleType(ScaleType.FIT_XY);
        return image;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM