Header ads

Header ads
» » BaseAdapter

BaseAdapter trong Android

Trong android, Một adapter liên kết dữ liệu với các thành phần UI. Nó điều khiển dữ liệu và gửi dữ liệu đến adapter view và sau đó lấy dữ liệu từ adapter view và hiển thị dữ liệu trên dữ liệu các view khác nhau như: ListView, GridView, Spinner. 

  • BaseAdapter là lớp adpater cơ sở cho các Adapter thường dùng khác như ArrayAdapter<T>, CursorAdapter, SimpleAdapter. BaseAdapter thường đóng vai trò Adapter cho các ListView Spinner sẽ được tìm hiểu trong các phần tiếp theo. 
  • Bất cứ khi nào khi bạn cần tùy chỉnh lại list trong ListView hoặc grid trong GridView, Chúng ta tạo riêng một adapter kế thừa từ BaseAdapter

Ví dụ sau tùy biến Adapter từ BaseAdapter:

  public class CustomAdapter extends BaseAdapter {    @Override  public int getCount() {  return 0;  }    @Override  public Object getItem(int i) {  return null;  }    @Override  public long getItemId(int i) {  return 0;  }    @Override  public View getView(int i, View view, ViewGroup viewGroup) {    return null;  }

Trong ví dụ trên chúng ta ghi đè (override) các phương thức BaseAdapter thường được sử dụng trong ListView, GridView, Spinner

1. getCount(): Phương thức này trả về số dòng của List 

  @Override  public int getCount() {  int count=arrayList.size(); //counts the total number of elements from the arrayList  return count;//returns the total count to adapter  }

2. getView(int i, View view, ViewGroup viewGroup): Phương thức này được gọi tự động các mục danh sách để sẵn sàng hiển thị. Trong phương thức chúng ta thiết lập layout cho danh sách các mục bằng cách sử dụng lớp LayoutInflater và sau đó thêm dữ liệu cho các view: ImageViewTextView .v.v.

  @Override  public View getView(int i, View view, ViewGroup viewGroup) {  view = inflter.inflate(R.layout.activity_gridview, null);//set layout for displaying items  ImageView icon = (ImageView) view.findViewById(R.id.icon);//get id for image view  icon.setImageResource(flags[i]);//set image of the item's  return view;  }

3. getItem(int i): : Phương thức này trả về Object dựa vào vị trí của đối tượng đó trong mảng dữ liệu

Vị trí sau lấy đối tượng thông qua vị trí

  @Override  public Object getItem(int i) {  return arrayList.get(i);  }

4. getItemId(int i): Phương thức này trả về id trên View của từng item mà adapter tạo ra.

Ví dụ sau chúng ta trả về vị trí

  @Override  public long getItemId(int i) {  return i;  }

 


Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một GridView để hiển thị danh hình ảnh các động vậtTiến hành tạo project, vào thư mục  res /layout -> activity_main.xml thiết kế giao diện sau:

Bước 1: Tạo một project tên là BaseAdapterFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code trong Linear Layout.

  <?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">    <GridView  android:id="@+id/simpleGridView"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:footerDividersEnabled="false"  android:numColumns="3" />  </LinearLayout>

Bước 3: Tạo mới một Activity activity_gridview.xml vào trong thư mục layout và thêm code sau:

  <?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/icon"          android:layout_width="100dp"          android:layout_height="100dp"          android:scaleType="fitXY"          android:layout_margin="5dp"          android:layout_gravity="center_horizontal" />  </LinearLayout>

Bước 4: Tạo mới một lớp CustomAdapter.java bên trong package và thêm code sau:

  package com.example.baseadapter;    import android.content.Context;  import android.view.LayoutInflater;  import android.view.View;  import android.view.ViewGroup;  import android.widget.BaseAdapter;  import android.widget.ImageView;    public class CustomBaseAdapter extends BaseAdapter {  Context context;  int animals[];  LayoutInflater inflter;    public CustomBaseAdapter(Context applicationContext, int[] animals) {  this.context = applicationContext;  this.animals = animals;  inflter = (LayoutInflater.from(applicationContext));  }    @Override  public int getCount() {  return animals.length;  }    @Override  public Object getItem(int i) {  return null;  }    @Override  public long getItemId(int i) {  return 0;  }    @Override  public View getView(int i, View view, ViewGroup viewGroup) {  view = inflter.inflate(R.layout.activity_gridview, null);  ImageView icon = (ImageView) view.findViewById(R.id.icon);  icon.setImageResource(animals[i]);  return view;  }  }

Bước 5: Open   src -> package -> MainActivity.java
Trong bước này chúng ta khởi tạo GridView. Tiếp theo, chúng ta tạo 1 mảng cho image. Lưu các hình ảnh vào thư mục drawable

  package com.example.baseadapter;    import android.app.Activity;  import android.os.Bundle;  import android.view.Menu;  import android.view.MenuItem;  import android.widget.GridView;    public class MainActivity extends Activity {  	GridView simpleGrid;  	int animals[] = {R.drawable.animal13, R.drawable.animal14, R.drawable.animal15, R.drawable.animal16, R.drawable.animal17, R.drawable.animal18, R.drawable.animal15, R.drawable.animal16, R.drawable.animal17};  	@Override  	protected void onCreate(Bundle savedInstanceState) {  		super.onCreate(savedInstanceState);  		setContentView(R.layout.activity_main);  		simpleGrid	=	(GridView) findViewById(R.id.simpleGridView);  		CustomBaseAdapter adapter	=	new  CustomBaseAdapter(getApplication(), animals);  		simpleGrid.setAdapter(adapter);  	}  	  }  

Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.


Kết quả khi chạy ứng dụng:


Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một ListView để hiển thị tên các nước cùng với lá cờ nước đóTiến hành tạo project, vào thư mục  res /layout -> activity_main.xml thiết kế giao diện sau:

Bước 1: Tạo một project tên là ListViewBaseAdapterFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code trong Linear Layout.

  <?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">        <ListView          android:id="@+id/simpleListView"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:divider="@color/material_blue_grey_800"          android:dividerHeight="1dp"          android:footerDividersEnabled="false" />  </LinearLayout>

Bước 3: Tạo mới một Activity activity_listview.xml vào trong thư mục layout và thêm code sau:

  <?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="horizontal">        <ImageView          android:id="@+id/icon"          android:layout_width="50dp"          android:layout_height="50dp"          android:src="@drawable/ic_launcher" />        <TextView          android:id="@+id/textView"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:layout_gravity="center"          android:padding="@dimen/activity_horizontal_margin"          android:textColor="#000" />  </LinearLayout>

Bước 4: Tạo mới một lớp CustomAdapter.java bên trong package và thêm code sau:

  package hiepsiit.com.listviewbaseadapter;    import android.content.Context;  import android.view.LayoutInflater;  import android.view.View;  import android.view.ViewGroup;  import android.widget.BaseAdapter;  import android.widget.FrameLayout;  import android.widget.ImageView;  import android.widget.TextView;    public class CustomBaseAdapter  extends BaseAdapter{  	 Context context;  	 String countryList[];  	 int flags[];  	 LayoutInflater inflter;  	public CustomBaseAdapter(Context context, String[] countryList, int[] flags) {  		super();  		this.context = context;  		this.countryList = countryList;  		this.flags = flags;  		inflter	= (LayoutInflater.from(context));  	}    	@Override  	public int getCount() {  		// TODO Auto-generated method stub  		return countryList.length;  	}    	@Override  	public Object getItem(int arg0) {  		// TODO Auto-generated method stub  		return null;  	}    	@Override  	public long getItemId(int position) {  		// TODO Auto-generated method stub  		return 0;  	}    	@Override  	public View getView(int position, View convertView, ViewGroup parent) {  		// TODO Auto-generated method stub  		convertView	=	inflter.inflate(R.layout.activity_listview, null);  		TextView country = (TextView) convertView.findViewById(R.id.textView);          ImageView icon = (ImageView) convertView.findViewById(R.id.icon);          country.setText(countryList[position]);          icon.setImageResource(flags[position]);  		return convertView;  	}	  }  

 Bước 5: Open   src -> package -> MainActivity.java
Trong bước này chúng ta khởi tạo ListView. Tiếp theo, chúng ta tạo 1 mảng cho image, 1 mảng cho tên image. Lưu các hình ảnh vào thư mục drawable

  package hiepsiit.com.listviewbaseadapter;    import android.app.Activity;  import android.os.Bundle;  import android.view.Menu;  import android.view.MenuItem;  import android.widget.ListView;    public class MainActivity extends Activity {  	ListView simpleList;      String countryList[] = {"India", "China", "australia", "Portugle", "America", "NewZealand"};      int flags[] = {R.drawable.india, R.drawable.china, R.drawable.australia, R.drawable.portugle, R.drawable.america, R.drawable.new_zealand};    	@Override  	protected void onCreate(Bundle savedInstanceState) {  		super.onCreate(savedInstanceState);  		setContentView(R.layout.activity_main);  		simpleList	=	 (ListView)findViewById(R.id.simpleListView);  		CustomBaseAdapter adapter	= 	new CustomBaseAdapter(this, countryList, flags);  		simpleList.setAdapter(adapter);  	}    	@Override  	public boolean onCreateOptionsMenu(Menu menu) {  		// Inflate the menu; this adds items to the action bar if it is present.  		getMenuInflater().inflate(R.menu.main, menu);  		return true;  	}    	@Override  	public boolean onOptionsItemSelected(MenuItem item) {  		// Handle action bar item clicks here. The action bar will  		// automatically handle clicks on the Home/Up button, so long  		// as you specify a parent activity in AndroidManifest.xml.  		int id = item.getItemId();  		if (id == R.id.action_settings) {  			return true;  		}  		return super.onOptionsItemSelected(item);  	}  }  

Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.


Kết quả khi chạy ứng dụng:


 



Cập nhật công nghệ từ Youtube tại link: https://www.youtube.com/channel/UCOxeYcvZPGf-mGLYSl_1LuA/videos
Để tham gia khóa học công nghệ truy cập link: http://thuvien.hocviendaotao.com
Mọi hỗ trợ về công nghệ email: dinhanhtuan68@gmail.com

About Học viện đào tạo trực tuyến

Xinh chào bạn. Tôi là Đinh Anh Tuấn - Thạc sĩ CNTT. Email: dinhanhtuan68@gmail.com .
- Nhận đào tạo trực tuyến lập trình dành cho nhà quản lý, kế toán bằng Foxpro, Access 2010, Excel, Macro Excel, Macro Word, chứng chỉ MOS cao cấp, IC3, tiếng anh, phần mềm, phần cứng .
- Nhận thiết kế phần mềm quản lý, Web, Web ứng dụng, quản lý, bán hàng,... Nhận Thiết kế bài giảng điện tử, số hóa tài liệu...
HỌC VIỆN ĐÀO TẠO TRỰC TUYẾN:TẬN TÂM-CHẤT LƯỢNG.
«
Next
Bài đăng Mới hơn
»
Previous
Bài đăng Cũ hơn