1

I am a beginner in android development. For a project, I would like to know how to implement a listview into a fragment ?

In my project, I have 3 fragments.

I have to retrieve all the contacts which are in my phone. (I am using this example => http://samir-mangroliya.blogspot.fr/p/android-read-contact-and-display-in.html). Then, I'll put them into one af the fragment, which contains a listview.

I am searching for many example, but it is only listview into ACTIVITY example.

Can you please help me ?

Best regards,

Tofuw

PS : Sorry for my bad english, I'm french :/

EDIT

Here is my code :

public class PhoneFrag extends ListFragment
{
private List<Contact>listecontact=new ArrayList<Contact>();

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}

public void onActivityCreated(Bundle savedInstanceState, Context context)
{
    super.onActivityCreated(savedInstanceState);

    String[]values=new String[]{};

    Cursor phones=context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);

    while(phones.moveToNext())
    {
        String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String num=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        Contact contact=new Contact();
        contact.setName(name);
        contact.setNum(num);

        listecontact.add(contact);
    }
    phones.close();

    ArrayAdapter<String>adapter=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_2, listecontact);
    setListAdapter(adapter);
}

I have an error at the third last line :

the constructor ArrayAdapter(FragmentActivity, int, List) is undefined

Can you help me please ?

Tofuw

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Tofuw
  • 908
  • 5
  • 16
  • 35
  • 2
    Why not just use a ListFragment? http://stackoverflow.com/questions/6510550/android-listview-in-fragment – the-ginger-geek Nov 14 '13 at 10:49
  • same as in an Activty. Build your xml. Get A instance of the ListView within its onCreateView(...) with `ListView lv = (ListView)fragmentRootView.findViewById(R.id.your_list_view);` I do not see your problem – A.S. Nov 14 '13 at 10:50
  • Hello, thanks for your answer ! I'm using the ListFragment :) – Tofuw Nov 14 '13 at 13:53

1 Answers1

3

Get your Fragment to extend ListFragment instead of Fragment.If you have used or looked at examples with ListActivity there is no need to associate this fragment with an xml layout file using setContentView(layout) anymore,Android creates a readymade Fragment with a ListView within it for your conveniance.Instead conveniance methods like setListAdapter(adapter) are available to you.However,in case you would like to access the ListView instance use the getListView().The Fragment seems to use onActivityCreated to do this:

I am guessing that you know fragments well enough to understand that this in ListActivity mean getActivity() in your ListFragment.

Here is the code that I found in the Android Fragment Documentation:

 public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // Populate list with our static array of titles.
    setListAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

    // Check to see if we have a frame in which to embed the details
    // fragment directly in the containing UI.
    View detailsFrame = getActivity().findViewById(R.id.details);
    mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

    if (savedInstanceState != null) {
        // Restore last state for checked position.
        mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
    }

    if (mDualPane) {
        // In dual-pane mode, the list view highlights the selected item.
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        // Make sure our UI is in the correct state.
        showDetails(mCurCheckPosition);
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("curChoice", mCurCheckPosition);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    showDetails(position);
}

/**
 * Helper function to show the details of a selected item, either by
 * displaying a fragment in-place in the current UI, or starting a
 * whole new activity in which it is displayed.
 */
void showDetails(int index) {
    mCurCheckPosition = index;

    if (mDualPane) {
        // We can display everything in-place with fragments, so update
        // the list to highlight the selected item and show the data.
        getListView().setItemChecked(index, true);

        // Check what fragment is currently shown, replace if needed.
        DetailsFragment details = (DetailsFragment)
                getFragmentManager().findFragmentById(R.id.details);
        if (details == null || details.getShownIndex() != index) {
            // Make new fragment to show this selection.
            details = DetailsFragment.newInstance(index);

            // Execute a transaction, replacing any existing fragment
            // with this one inside the frame.
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (index == 0) {
                ft.replace(R.id.details, details);
            } else {
                ft.replace(R.id.a_item, details);
            }
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.commit();
        }

    } else {
        // Otherwise we need to launch a new activity to display
        // the dialog fragment with selected text.
        Intent intent = new Intent();
        intent.setClass(getActivity(), DetailsActivity.class);
        intent.putExtra("index", index);
        startActivity(intent);
    }
}

}

You can also use methods like setEmptyText and setListShown to display a message in case your Cursor has no rows and toggle the visibility of your listView respectively.Also,Android's Loader Framework is only supported with a Fragment and not an Activity in the support library.

bcdan
  • 1,438
  • 1
  • 12
  • 25
vamsiampolu
  • 6,328
  • 19
  • 82
  • 183
  • Thanks for your answer @user2309862. But now, I have an other problem. Can you help me please ? I'll post my code below, and detail more precisely. – Tofuw Nov 14 '13 at 13:55