一个Activity左右分别显示一个Fragment

 前天去面试,面试后让当场撸代码,面试官让写左边一个Fragment加载listview,右边也是一个fragment,加载Listview。之前几乎没写过这个,不过经过各种调试,最后撸出来了 ,效果差一点,我左边用的是ListFragment,右边是一个fragment,加载的是textview,不是listview(右边的不太符合要求)。这里把它补充完整,记录下来。
这种文章网上有很多,代码大致雷同,这里只介绍自己实现过程中遇到的问题
大致效果就是这样的,

这里写图片描述

介绍:
一个主MainActivity,里面加载了
左边一个LeftListFragment,右边一个RightListFragment
LeftListFragment 中ListView中每一行的显示内容,采用系统默认的layout:
android.R.layout.simple_list_item_1
RightListFragment 中ListView中每一行的显示内容,采用自定义的layout:
R.layout.layout_listview_item
点击左边的每一项时,右边的ListFragment更新数据

代码布局
这里写图片描述

 

一、MainActivity
1.1 类文件

MainActivity.java

package com.fragment.demo;

import android.app.FragmentTransaction;
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);

//布局文件中如果没有使用fragment标签,使用的是LinearLayout或者Framelayout,代码中需添加如下代码加载Fragment
        LeftListFragment leftListFragment = new LeftListFragment();
        RightListFragment rightListFragment = new RightListFragment();
        //DetailFragment detailFragment = DetailFragment.newInstance("default");
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.add(R.id.left_fragment,leftListFragment,"leftListFragment");//添加leftListFragment并为其设置tag leftListFragment
        //transaction.add(R.id.right_fragment,detailFragment,"detailFragment");
        transaction.add(R.id.right_fragment,rightListFragment,"rightListFragment");添加rightListFragment并为其设置tag rightListFragment
        transaction.commit();
    }
}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24

1.2布局文件

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="horizontal">
    <FrameLayout//此处也可以使用LinearLayout,或者使用fragment,如果使用fragment需为此标签添加class属性
        android:id="@+id/left_fragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />
    <FrameLayout
        android:id="@+id/right_fragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"//权重为了 平分布局
        />
</LinearLayout>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

二、ListFragement介绍

ListFragment继承于Fragment。因此它具有Fragment的特性,能够作为activity中的一部分,目的也是为了使页面设计更加灵活。

相比Fragment,ListFragment的内容是以列表(list)的形式显示的。
ListFragment的布局默认包含一个list view。因此,
在ListFragment对应的布局文件中,必须指定一个 android:id 为”@android:id/list”的ListView控件! 若用户向修改list view的,可以在onCreateView(LayoutInflater, ViewGroup, Bundle)中进行修改。当然,用户也可以在ListFragment的布局中包含其它的控件。
2.1 LeftListFragment
2.11 类文件

LeftListFragment.java

package com.fragment.demo;

import android.app.ListFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * Created by wangqixu on 2017/10/17.
 */

public class LeftListFragment extends ListFragment {
    String arrays[] = {"星期一","星期二","星期三","星期四","星期五","星期六"};

    public LayoutInflater mInflater;

    public static final String LeftListFragmentTag = "leftListFragmentTag";
    public static LeftListFragment newInstance(String str){
        LeftListFragment leftListFragment = new LeftListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(LeftListFragmentTag,str);
        leftListFragment.setArguments(bundle);
        return leftListFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInflater = getActivity().getLayoutInflater();
        this.setListAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,arrays));//为LeftListFragment设置适配器,其中LeftListFragment中的listview的每一项的布局使用系统自带布局android.R.layout.simple_list_item_1(里面只有个textview)
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = mInflater.inflate(R.layout.layout_leftfragment,container,false);//解析LeftListFragment的布局文件
        return view;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        /*DetailFragment detailFragment = new DetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString(DetailFragment.DetailFragmentArg,String.valueOf(position));
        detailFragment.setArguments(bundle);
        getFragmentManager().beginTransaction().replace(R.id.right_fragment,detailFragment).commit();
        */

        RightListFragment  rightListFragment = (RightListFragment) getFragmentManager().findFragmentByTag("rightListFragment");//当点击LeftListFragment中listview的某一项时,会触发此方法。通过tag找到rightListFragment,MainActivity中add Fragment时设置的此tag,然后调用次Fragment中的refreshData()方法刷新数据,此方法会从新设置adapter
//getFragmentManager().beginTransaction().replace(R.id.right_fragment,rightListFragment).commit();
        rightListFragment.refreshData(position);

    }
}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59

2.12 布局

下面是LeftListFragment对应的layout示例:layout_leftfragment.xml

<?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">
    <ListView
        android:id="@android:id/list"//必须写这个id,@id/android:list,@+id/android:list,这两种写法也可以,自己尝试下
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

2.3 RightListFragment
2.31 类文件

RightListFragment.java

package com.fragment.demo;

import android.app.ListFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangqixu on 2017/10/17.
 */

public class RightListFragment extends ListFragment {

    public LayoutInflater mInflater;

    public static final String LeftListFragmentTag = "leftListFragmentTag";
    public static RightListFragment newInstance(String str){
        RightListFragment leftListFragment = new RightListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(LeftListFragmentTag,str);
        leftListFragment.setArguments(bundle);
        return leftListFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInflater = getActivity().getLayoutInflater();
        refreshData(0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = mInflater.inflate(R.layout.layout_rightfragment,container,false);
        return view;
    }

    public void refreshData(int position){
        this.setListAdapter(new SimpleAdapter(this.getActivity(),getData(position),R.layout.layout_listview_item,from,to));
    }

    final String[] from = {"title","info"};下面会使用SimpleAdapter,此数组中的内容将作为map中的key,构造SimpleAdapter时要求传入List集合,List中的元素要求是map
    final int[] to = new int[]{R.id.class_name,R.id.teacher_name};//listview中某一项布局的子元素id//将数组中的内容修改为R.id.title,R.id.info更好理解些
    String[] className = {"英语","文学鉴赏","电影鉴赏","数据结构","大学物理","体育"};//将className数组名修改为classNameInfo更好理解些
    String[] teacher = {"王五","李四","李磊","董卿","张雪","李梅梅"};
//将teacher数组名修改为teacherInfo更好理解些
public List<Map<String,Object>> getData(int position){
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        //为listview添加一项内容,这项内容使用的布局文件是layout_listview_item.xml文件
        //layout_listview_item.xml布局文件有两个textview,key为title的使用一个textview/class_name
        //key为info的使用一个textview/teacher_name
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("title","课程名称");
        map.put("info",className[position]);
        list.add(map);


        map = new HashMap<String,Object>();
        map.put("title","教师名称");
        map.put("info",teacher[position]);
        list.add(map);
        return list;
    }

 

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

    }
}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83

2.32 RightListFragment的布局文件

下面是RightListFragment对应的layout示例:
layout_rightfragment.xml(内容和layout_leftfragment.xml一样)

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

2.33 listview中某一项的布局文件

layout_listview_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/class_name"//在map中对应的key 为title,将此id改为title读代码时更好理解
        android:textSize="15sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/teacher_name"//在map中对应的key 为info,将此id改为info,读代码时更好理解
        android:textSize="30sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18

这里写图片描述


这里写图片描述
参考
http://blog.csdn.net/kakaxi1o1/article/details/29368645
http://www.cnblogs.com/mstk/p/5789265.html
---------------------  
作者:一小沫一  
来源:CSDN  
原文:https://blog.csdn.net/w690333243/article/details/78274353  
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以按照以下步骤实现: 1. 在 Android Studio 中创建一个新项目,选择 Kotlin 语言作为主要语言。 2. 在 app 模块下的 build.gradle 文件中添加以下依赖: ``` implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.recyclerview:recyclerview:1.1.0' ``` 3. 在 res/layout 目录下创建一个新的布局文件,例如 activity_main.xml,添加一个垂直的 LinearLayout 布局,将其分成两个部分,左侧为 RecyclerView,右侧为 FrameLayout,如下所示: ``` <?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"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" /> <FrameLayout android:id="@+id/container" android:layout_width="0dp" android:layout_weight="2" android:layout_height="match_parent" /> </LinearLayout> ``` 4. 在 res/layout 目录下创建一个新的布局文件,例如 fragment_detail.xml,用于显示右侧的 Fragment 内容。 5. 在 MainActivity.kt 中编写代码,实现 RecyclerView 和 Fragment显示和切换: ``` class MainActivity : AppCompatActivity() { private lateinit var recyclerView: RecyclerView private lateinit var container: FrameLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) recyclerView = findViewById(R.id.recycler_view) container = findViewById(R.id.container) val items = listOf("Item 1", "Item 2", "Item 3", "Item 4", "Item 5") recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = ItemAdapter(items) { item -> supportFragmentManager.beginTransaction() .replace(R.id.container, DetailFragment.newInstance(item)) .commit() } } } class ItemAdapter( private val items: List<String>, private val onClick: (String) -> Unit ) : RecyclerView.Adapter<ItemViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { val view = LayoutInflater.from(parent.context) .inflate(android.R.layout.simple_list_item_1, parent, false) return ItemViewHolder(view) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val item = items[position] holder.textView.text = item holder.itemView.setOnClickListener { onClick(item) } } override fun getItemCount(): Int = items.size } class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textView: TextView = itemView.findViewById(android.R.id.text1) } class DetailFragment : Fragment() { companion object { private const val ARG_ITEM = "item" fun newInstance(item: String) = DetailFragment().apply { arguments = Bundle().apply { putString(ARG_ITEM, item) } } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_detail, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val item = arguments?.getString(ARG_ITEM) view.findViewById<TextView>(R.id.text).text = item } } ``` 6. 运行应用程序,可以看到左侧是一个包含几个项目的列表,右侧是一个空白的区域。当单击列表中的一个项目时,右侧将显示一个包含项目名称的 Fragment
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值