ListFragment的简单使用

public class DataUtils {
    public static final String[] TITLES = {"title1", "title2", "title3", "title4", "title5"};
    public static final String[] DETAILS = {"this is title1", "this is title2", "this is title3", "this is title4", "this is title5"};
}
public class DetailFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        //取出数据
        String detail = getArguments().getString("DETAIL");
        //设置
        textView.setText(detail);
        return textView;

    }
}
public class TitleListFragment extends ListFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //设置listview为单选模式
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);


        //给ListView设置adapter显示列表
        setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.list_item, DataUtils.TITLES));

        //默认选中第一个item
        getListView().setItemChecked(0, true);

        showDetail(0);
    }

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

    }

    public void showDetail(int position) {
        //创建DetailFragment
        DetailFragment fragment = new DetailFragment();
        //将对应的数据带过去
        Bundle bundle = new Bundle();
        bundle.putString("DETAIL", DataUtils.DETAILS[position]);
        fragment.setArguments(bundle);
        //替换fl_main_content
        getFragmentManager().beginTransaction().replace(R.id.fl_main_show, fragment).commit();
    }
}
<?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">

    <fragment
        android:id="@+id/fra_main_list"
        android:name="com.example.fragment.TitleListFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <FrameLayout
        android:id="@+id/fl_main_show"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2">

    </FrameLayout>


</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="?android:attr/activatedBackgroundIndicator">

</TextView>

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页