Fragment的简单使用二

推荐:

今日写了一个侧面点击的 Fragment (类似于电商类),做一下记录,下面是效果图:

       

下面是主要内容:

  • MainActivity 代码和 activity_main 布局文件
  • Adapter 代码和 adapter 布局文件
  • MainFragment 代码 和 fragment_main 布局文件

这是上面效果图的源码&&&

1. MainActivity 代码和 activity_main 布局文件

下面是 MainAcitvity 中的代码:

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    private RecyclerView recyclerView;
    private List<String> titleList;//标题列表
    private List<Fragment> fragmentList;//fragment列表
    private Adapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);

        //设置侧面标题以及适配器
        setTitleList();
        //添加fragment并设置显示位置为第一个
        setFragment();
    }

    //设置侧面标题以及适配器
    private void setTitleList() {
        //模拟,为标题添加数据
        titleList = new ArrayList<>();
        titleList.add("男装");
        titleList.add("女装");
        titleList.add("童装");
        titleList.add("男鞋");
        titleList.add("女鞋");
        //设置侧面标题适配器
        adapter = new Adapter(this, titleList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter.setmOnItemClickListerer(new Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, String type) {
                setFragmentSite(position);
            }
        });
    }

    //添加fragment并设置显示位置为第一个
    private void setFragment() {
        fragmentList = new ArrayList<>();
        android.app.FragmentTransaction fTransaction = getFragmentManager().beginTransaction();
        //将 MainFragment 添加到列表中,以供显示
        for (int i = 0; i < titleList.size(); i++) {
            fragmentList.add(new MainFragment(titleList.get(i)));
            fTransaction.add(R.id.fl_content, fragmentList.get(i));
        }
        fTransaction.commitAllowingStateLoss();
        //设置fragment位置;默认第一个,即传0;
        setFragmentSite(0);
    }

    //设置fragment位置
    private void setFragmentSite(int position) {
        //防止为空
        if (fragmentList == null || fragmentList.size() == 0) {
            setFragment();
            return;
        }
        android.app.FragmentTransaction fTransaction = getFragmentManager().beginTransaction();
        //隐藏所有的Fragment
        for (int i = 0; i < fragmentList.size(); i++) {
            fTransaction.hide(fragmentList.get(i));
        }
        //显示特定的Fragment
        fTransaction.show(fragmentList.get(position)).commitAllowingStateLoss();
    }
}

注意:

  • 我在上面导入的是 android.app.Fragment;   不要与  import android.support.v4.app.Fragment;  搞混了。
  • 不要忘记在 build.gradle 文件中添加:implementation 'com.android.support:recyclerview-v7:26.1.0'

下面是 activity_main 的布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!--标题-->
    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="标题"
        android:textSize="18dp"
        android:textColor="#000000"
        android:gravity="center"/>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="90dp"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:background="#FFF3F4F6"
        android:layout_below="@+id/tv_title"/>
    <FrameLayout
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/recyclerView"
        android:layout_below="@+id/tv_title"/>
</RelativeLayout>

2. Adapter 代码和 adapter 布局文件

下面是侧面标题栏的列表适配器 Adapter 中代码:

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
    private List<String> list = new ArrayList<>();
    private HashMap<Integer, RelativeLayout> mapRl = new HashMap<>();//存储背景
    private HashMap<Integer, ImageView> mapIv = new HashMap<>();//存储图标
    private HashMap<Integer, TextView> mapTv = new HashMap<>();//存储标题

    //接口回调
    public interface OnItemClickListener {
        void onItemClick(int position, String type);
    }

    public Adapter.OnItemClickListener mOnItemClickListerer;

    public void setmOnItemClickListerer(Adapter.OnItemClickListener listerer) {
        this.mOnItemClickListerer = listerer;
    }

    public Adapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.adapter, parent, false);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        holder.tv_name.setText(list.get(position));
        mapRl.put(position, holder.rl_all);//储存背景
        mapIv.put(position, holder.iv_icon);//储存图片
        mapTv.put(position, holder.tv_name);//储存名称
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //将所有字体颜色,图片背景,遍历设置颜色
                for (HashMap.Entry<Integer, RelativeLayout> entry : mapRl.entrySet()) {
                    entry.getValue().setBackgroundColor(Color.parseColor("#FFF3F4F6"));
                }
                for (HashMap.Entry<Integer, ImageView> entry : mapIv.entrySet()) {
                    entry.getValue().setVisibility(View.GONE);
                }
                for (HashMap.Entry<Integer, TextView> entry : mapTv.entrySet()) {
                    entry.getValue().setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    entry.getValue().setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                }
                holder.rl_all.setBackgroundColor(Color.parseColor("#FFFFFFFF"));//设置背景
                holder.iv_icon.setVisibility(View.VISIBLE);
                holder.tv_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);//设置字体大小
                holder.tv_name.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//设置高亮
                mOnItemClickListerer.onItemClick(position, "");
            }
        });
        //默认选中第一项
        if (position == 0) {
            holder.rl_all.setBackgroundColor(Color.parseColor("#FFFFFFFF"));
            holder.iv_icon.setVisibility(View.VISIBLE);
            holder.tv_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            holder.tv_name.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        } else {
            holder.rl_all.setBackgroundColor(Color.parseColor("#FFF3F4F6"));
            holder.iv_icon.setVisibility(View.GONE);
            holder.tv_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            holder.tv_name.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_icon;
        TextView tv_name;
        RelativeLayout rl_all;
        public MyViewHolder(View itemView) {
            super(itemView);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_name = itemView.findViewById(R.id.tv_name);
            rl_all = itemView.findViewById(R.id.rl_all);
        }
    }
}

下面是布局文件 adapter 的代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="90dp"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:background="#FFFFFF"
    android:id="@+id/rl_all">
    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="4dp"
        android:layout_height="20dp"
        android:background="#FFF24C7C"
        android:layout_centerVertical="true"/>

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="女装"
        android:textSize="15dp"
        android:textColor="#FF333333"
        android:gravity="center"
        android:layout_centerInParent="true"/>
</RelativeLayout>

3. MainFragment 代码 和 fragment_main 布局文件

最后看一下 MainFragment 中的代码:

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class MainFragment extends Fragment {
    private View view;
    private String title;
    private TextView tv_text;

    public MainFragment(String title) {
        this.title = title;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = View.inflate(getActivity(),R.layout.fragment_main,null);

        tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(title);
        return view;
    }
}

要注意的也是要导入的 Fragment 包不要错了

下面是 fragment_main 文件中的代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#000000"
        android:textSize="20dp"
        android:gravity="center"/>
</LinearLayout>

当写到这个地方,以上效果图的效果便实现了。

这是上面效果图的源码&&&

推荐:

猜你喜欢

转载自blog.csdn.net/wuqingsen1/article/details/83585091