-1

我是 android 技术的新手。我想ListView使用Fragments. 我已经在谷歌上搜索了它,但我没有得到它。所以请帮助我。

4

1 回答 1

1

我在我的应用程序中有一个屏幕,包含左右两个列表片段以及自定义列表视图。希望这是你需要的,使用这些,让我知道它是否对你有帮助?

这是包含片段的类

  public class MoreChannelsActivity extends FragmentActivity 
    implements ChannelsMenuFragment.OnHeadlineSelectedListener {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        ChannelsMenuFragment firstFragment = new ChannelsMenuFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    }
}

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the ChannelsMenuFragment

    // Capture the article fragment from the activity layout

  /// ChannelsSubMenuFragment articleFrag = (ChannelsSubMenuFragment) getSupportFragmentManager().findFragmentById(R.id.channels_fragment);

TestSubMenuFragment articleFrag = (TestSubMenuFragment) getSupportFragmentManager().findFragmentById(R.id.channels_fragment);

    if (articleFrag != null) {
        // If article frag is available, we're in two-pane layout...

        // Call a method in the ChannelsSubMenuFragment to update its content
      // articleFrag.updateArticleView(position);
           articleFrag.updateListView(position);

    } else {
        // If the frag is not available, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        TestSubMenuFragment newFragment = new TestSubMenuFragment();
        Bundle args = new Bundle();
        args.putInt(TestSubMenuFragment.ARG_POSITION, position);
        newFragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }
   }
   }

这是包含片段的xml...

      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<fragment
    android:id="@+id/menus_fragment"
    android:name="com.example.android.fragments.ChannelsMenuFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />
<View
    android:layout_width="3px"
    android:layout_height="fill_parent"
    android:layout_marginTop="0dp"
    android:background="#FF909090" />

<fragment
    android:id="@+id/channels_fragment"
    android:name="com.example.android.fragments.TestSubMenuFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2" />

  </LinearLayout>

这是列表活动类

 public class ChannelsMenuFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;

// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
    /** Called by ChannelsMenuFragment when a list item is selected */
    public void onArticleSelected(int position);
}

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

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    // Create an array adapter for the list view, using the AudioVideoChannelsList headlines array
    setListAdapter(new ArrayAdapter<String>(getActivity(), layout, AudioVideoChannelsList.Menus));
}

@Override
public void onStart() {
    super.onStart();

    // When in two-pane layout, set the listview to highlight the selected list item
    // (We do this during onStart because at the point the listview is available.)
    if (getFragmentManager().findFragmentById(R.id.channels_fragment) != null) {
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception.
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Notify the parent activity of selected item
    mCallback.onArticleSelected(position);

    // Set the item as checked to be highlighted when in two-pane layout
    getListView().setItemChecked(position, true);
    }
   }

这是我们提供给列表适配器的名为 AudioVideoChannelsList 的数据类

     public class AudioVideoChannelsList {

static String[] Menus = {
    "Channel One",
    "Channel Two"
};



static String[] ChannelsList1 = {
   "Country",
   "Genre",
   "Language"
  };

    static String[] ChannelsList = {
    "Article One\n\nExcepteur pour-over occaecat squid biodiesel umami gastropub, nulla           laborum salvia dreamcatcher fanny pack. Ullamco culpa retro ea, trust fund excepteur eiusmod direct trade banksy nisi lo-fi cray messenger bag. Nesciunt esse carles selvage put a bird on it gluten-free, wes anderson ut trust fund twee occupy viral. Laboris small batch scenester pork belly, leggings ut farm-to-table aliquip yr nostrud iphone viral next level. Craft beer dreamcatcher pinterest truffaut ethnic, authentic brunch. Esse single-origin coffee banksy do next level tempor. Velit synth dreamcatcher, magna shoreditch in american apparel messenger bag narwhal PBR ennui farm-to-table.",
    "Article Two\n\nVinyl williamsburg non velit, master cleanse four loko banh mi. Enim kogi keytar trust fund pop-up portland gentrify. Non ea typewriter dolore deserunt Austin. Ad magna ethical kogi mixtape next level. Aliqua pork belly thundercats, ut pop-up tattooed dreamcatcher kogi accusamus photo booth irony portland. Semiotics brunch ut locavore irure, enim etsy laborum stumptown carles gentrify post-ironic cray. Butcher 3 wolf moon blog synth, vegan carles odd future."
};

static String[] ChannelsList2 = {
     "Country2",
     "Genre2",
     "Language2"
   };
  }

这是第二个列表活动类

          public class TestSubMenuFragment extends ListFragment {

// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
    /** Called by ChannelsMenuFragment when a list item is selected */
    public void onArticleSelected(int position);
}

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

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_2;

    // Create an array adapter for the list view, using the AudioVideoChannelsList headlines array
    setListAdapter(new ArrayAdapter<String>(getActivity(), layout, AudioVideoChannelsList.ChannelsList1));
 }

@Override
public void onStart() {
    super.onStart();

    // When in two-pane layout, set the listview to highlight the selected list item
    // (We do this during onStart because at the point the listview is available.)
    if (getFragmentManager().findFragmentById(R.id.channels_fragment) != null) {
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
}
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
public void updateListView(int pos)
{
    if(pos==0)
    {
     int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
             android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_2;

     // Create an array adapter for the list view, using the AudioVideoChannelsList headlines array
     setListAdapter(new ArrayAdapter<String>(getActivity(), layout, AudioVideoChannelsList.ChannelsList1));
    }
    else
    {
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 :      android.R.layout.simple_list_item_2;

        // Create an array adapter for the list view, using the AudioVideoChannelsList headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, AudioVideoChannelsList.ChannelsList2));

    }
}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception.
    try {

    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Notify the parent activity of selected item


    // Set the item as checked to be highlighted when in two-pane layout

  }
   }
于 2013-01-07T10:43:19.083 回答