Fragment意思为碎片、片段。
在Android中有些Activity在手机上看起来很美观,但放在屏幕更大的平板类的设备上,可能就不一样了,而Fragment能在一个Activity中内嵌多个独立的小Activity,有效的解决了app在大屏设备上的显示问题。

运行环境

  • Windows 10
  • Android Studio Arctic Fox (2020.3.1)
  • jdk1.7.0_67

新建一个项目

添加控件

在布局文件activity_main.xml中添加两个FrameLayout控件。

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

android:layout_width="0dp"android:layout_weight="2"需要搭配使用,表示id为leftcontainer的占屏幕的2份(即2/5),id为rightcontainer占屏幕3份(即3/5)。

新建Fragment

在Android Studio界面中点击右上角的File,依次选择new->Java Class,命名为LeftFragmentRightFragment。 再点击new->XML->layout XML File,命名为leftfragmentlayout,rightfragmentlayout
布局文件名不可大写。
在LeftFragment.java和RightFragment.java中继承Fragment。注意Fragment的版本。

20211101224054.jpg
20211101224054.jpg

接着输入

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.leftfragmentlayout,container,false);

在新建的两个布局文件中输入以下代码。

//leftfragmentlayout.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="vertical"
    android:background="#cccc11">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/title_list"/>
</LinearLayout>
//rightfragmentlayout.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="vertical"
    android:background="#fcabff">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv_title"
        android:gravity="center" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tv_content" />

</LinearLayout>

android:background="#fcabff"是为了能区分两个Fragment,实际操作中不需要这个。

初始化

在MainActivity中对新建的Fragment初始化。

private void initView() {
        LeftFragment leftFragment=new LeftFragment();
        RightFragment rightFragment=new RightFragment();
        FragmentManager manager=getSupportFragmentManager();
        FragmentTransaction transaction=manager.beginTransaction();
        transaction.add(R.id.leftcontainer,leftFragment);
        transaction.add(R.id.rightcontainer,rightFragment);
        transaction.commit();
    }

数据传递

定义数据,我们直接给 Fragment几串数据。

private String[] titles={"标题1","标题2","标题3"}
private String[][] titlesAndContents={{"标题1","正文1"},{"标题2","正文2"},{"标题3","正文3"}

public String[] getTitles() {
return titles;
}
public String[][] getTitlesAndContents() {
return titlesAndContents;
}

数据接收
LeftFragment

//LeftFragment.java


private  View view;
private String[] titles;
private String[][] titlesAndContents;
private ListView listView;
//此处省略了一部分代码,在上文已经写过。

MainActivity mainActivity=(MainActivity) getActivity();
titles=mainActivity.getTitles();
titlesAndContents=mainActivity.getTitlesAndContents();
if(view!=null){
listView=view.findViewById(R.id.title_list);
MyAdapter adapter=new MyAdapter(getContext(),titles);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 在LeftFragment中获取RightFragment的实例
RightFragment rightFragment=(RightFragment) ((MainActivity)getActivity()).getSupportFragmentManager().findFragmentById(R.id.rightcontainer);
rightFragment.setText(titlesAndContents[position]);
}
});
return view;

RightFragment

//RightFragment.java
private View view;
private String[][] titlesAndContents;
private TextView tv_title,tv_content;

//此处省略了一部分代码,在上文已经写过。

MainActivity mainActivity=(MainActivity) getActivity();
        titlesAndContents=mainActivity.getTitlesAndContents();
        if(view!=null){
            tv_title=(TextView) view.findViewById(R.id.tv_title);
            tv_content=(TextView)view.findViewById(R.id.tv_content);
            setText(titlesAndContents[0]);
        }
        return view;
    }
    public  void setText(String[] strings){
        tv_title.setText(strings[0]);
        tv_content.setText(strings[1]);
    }
}

上述代码省略了导包的代码,请自己添加(波浪线处按住Alt+Enter)。

自定义适配器

为了能在Activity中自由切换我们还需要自定义一个适配器。
新建一个MyAdapter.java

public class MyAdapter extends BaseAdapter {
    private Context context;
    private String[] titles;

    public MyAdapter(Context context, String[] titles) {
        this.context = context;
        this.titles = titles;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public Object getItem(int position) {
        return titles[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder=null;
        if(convertView==null){
            convertView= LayoutInflater.from(context).inflate(R.layout.title_item_layout,null);
            holder=new ViewHolder();
            holder.textView=(TextView)convertView.findViewById(R.id.tv_title);
            convertView.setTag(holder);
        }else{
            holder=(ViewHolder) convertView.getTag();
        }
        holder.textView.setText(titles[position]);
        return convertView;
    }
    class ViewHolder{
        TextView textView;
    }
}

最终效果

2021-11-01 23-11-3820211112316152.gif
2021-11-01 23-11-3820211112316152.gif

完整代码下载连接

[hide] [x-btn type='secondary' icon='' href='https://pan.baidu.com/s/1Q3Xt1DCsEsPzTqVJwZGSew?pwd=hzk7' content='Fragment.rar' /] 提取码:hzk7 [/hide]