List Fragment trong Android

Thư viện tĩnh của Android hỗ trợ ListFragment. Được sử dụng để viết các ứng dụng chạy trên các nền tảng trước Android 3.0. Khi đang chạy trên nền tảng Android 3.0 hoặc phiên bản nâng cấp, thì trình triển khai này vẫn được sử dụng.

Trình triển khai cơ bản của List Fragment là để tạo danh sách các mục trong các Fragment.

List Fragment trong Android

LIST FRAGMENT

Ví dụ

Ví dụ sau giải thích cho bạn cách tạo riêng cho mình List Fragment dựa vào arrayAdapter. Bạn theo các bước tương tự như trong Ví dụ Hello World.

Bước Miêu tả
1 Bạn sử dụng Android Studio để tạo một ứng dụng Android với tên làSimpleListFragment dưới một package com.example.listfragmentdemo
2 Sửa đổi res/values/string.xml để thêm các hằng chuỗi mới
3 Tạo một layout gọi là list_fragment.xml dưới thư mục res/layout để định nghĩa List Fragment và thêm thẻ(<fragment>) tới activity_main.xml
4 Tạo một myListFragment.java, được đặt trong java/myListFragment.java và nó chứa onCreateView(),onActivityCreated()OnItemClickListener()
7 Chạy ứng dụng trên Android Emulator và kiểm tra kết quả các thay đổi đã thực hiện trong ứng dụng

Trước khi bắt đầu viết code, chúng ta khởi tạo các hằng chuỗi bên trong string.xml dưới thư mục res/values directory

<?xml version="1.0" encoding="utf-8"?7gt;
<resources>
   <string name="app_name">ListFragmentDemo</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="imgdesc">imgdesc</string>
   
   <string-array name="Planets">
      <item>Sun</item>
      <item>Mercury</item>
      <item>Venus</item>
      <item>Earth</item>
      <item>Mars</item>
      <item>Jupiter</item>
      <item>Saturn</item>
      <item>Uranus</item>
      <item>Neptune</item>
   </string-array>

</resources>

Dưới đây là nội dung của res/layout/activity_main.xml file. Nó chứa linear layout và thẻ fragment.

<?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" >
   
   <fragment
      android:id="@+id/fragment1"
      android:name="com.pavan.listfragmentdemo.MyListFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

</LinearLayout>

Nội dung của res/layout/list_fragment.xml file. Nó chứa linear layout, list view và text view.

<?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="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TextView>

</LinearLayout>

Còn đây là nội dung của src/main/java/myListFragment.java file. Trước khi viết code, bạn cần theo các bước sau:

  • Tạo một lớp MyListFragment và kế thừa nó từ ListFragment.
  • Bên trong phương thức onCreateView(), tạo view với list_fragment xml layout đã được định nghĩa ở trên. (ở đây ta dùng flate thay cho create, và hiểu nôm na là chúng ta sẽ tạo một view, một layout từ xml file đã có sẵn, còn với create thì tạo mới hoàn toàn.)
  • Bên trong phương thức onActivityCreated(), tạo một arrayadapter từ Resource, chẳng hạn như bạn sử dụng string array là R.array.planet mà bạn có thể tìm thấy bên trong string.xml và thiết lập adapter này tới listview và cũng thiết lập OnItemClickListener.
  • Bên trong phương thức OnItemClickListener(), hiển thị một thông báo toast với tên Item được click.
package com.example.listfragmentdemo;

import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MyListFragment extends ListFragment implements OnItemClickListener {
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.list_fragment, container, false);
      return view;
   }
   
   @Override
   public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);
      setListAdapter(adapter);
      getListView().setOnItemClickListener(this);
   }
   
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
      Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
   }
}

Nội dung của MainActivity.java là:

package com.example.listfragmentdemo;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

Nội dung của manifest.xml được đặt tại res/AndroidManifest.xml là:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.listfragmentdemo"
   android:versionCode="1"
   android:versionName="1.0" >
 
   <application
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/title_activity_main" >
            
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER"/>
         </intent-filter>
           
      </activity>
       
   </application>
</manifest>

Chạy ứng dụng Android

 

Bây giờ, chạy ứng dụng SimpleListFragment đã tạo ở trên. Giả sử bạn đã tạo AVD trong khi cài đặt. Để chạy ứng dụng từ Android Studio, mở activity file và nhấn biểu tượng Run từ thanh công cụ.

List Fragment trong Android

Bình luận về bài viết này