ListFragment
A fragment that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item.
The basic implementation of list fragment is for creating list of items in fragments.
Get GITHUB code from Here.
Let’s have a look at the simple example of android ListFragment.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lenovo.listfragmentapp.MainActivity"> <FrameLayout android:id="@+id/frame_layout" class="com.example.lenovo.listfragmentapp.FragmentA" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
fragment1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lenovo.listfragmentapp.FragmentA"> <ListView android:id="@id/android:list" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView> </LinearLayout>
MainActivity.Java
package com.example.lenovo.listfragmentapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentA fragment1 = new FragmentA(); getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragment1).commit(); } }
Fragment1.Java
package com.example.lenovo.listfragmentapp; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class Fragment1 extends ListFragment { String[] code_name = {"Froyo", "GingerBread", "HoneyComb", "IceCream Sandwich", "JellyBean", "Kitkat", "Lollipop", "Marshmallow", "Nougat", "Oreo"}; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment1, container, false); ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1, code_name); setListAdapter(adapter); return view; } @Override public void onListItemClick(ListView l, View v, int position, long id) { Toast.makeText(getActivity().getBaseContext(), code_name[position], Toast.LENGTH_SHORT).show(); } }
When you run the app it will look like this: