本次课程为Fragment为主题,课程的示例仿美团外卖界面,不同于底部导航栏的Fragment案例,此界面分为左侧切换与顶部切换。本文先是发布代码与效果,后续讲解将会在后续补充。先看看效果:
首先是布局文件代码:Activity布局:activity_main.xml:
首先父布局用的LinearLayout布局,并通过代码:android:orientation="vertical"来设置布局方向为垂直布局。界面分为顶部导航栏、左侧菜单栏、右侧菜单栏,由此分为三大部分子布局
分别用到了RelativeLayout、LinearLayout(左右布局放在一个LinearLayout,设置布局方向为水平即可)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="4dp"
android:gravity="center_vertical">
<TextView
android:id="@+id/tv_order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="4dp"
android:textSize="16sp"
android:text="点菜"
/>
<TextView
android:id="@+id/tv_discuss"
android:layout_toRightOf="@id/tv_order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="4dp"
android:textSize="16sp"
android:text="评价"
/>
<TextView
android:id="@+id/tv_business"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="@id/tv_discuss"
android:textSize="16sp"
android:text="商家"
/>
<TextView
android:layout_width="70dp"
android:layout_height="30dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="4dp"
android:textSize="12sp"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
android:background="@drawable/friend_list"
android:gravity="center"
android:textColor="#ef842c"
android:text="好友拼单"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<fragment
android:id="@+id/left"
android:name="com.example.student.LeftFragment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/fragment_left"/>
<fragment
android:id="@+id/right"
android:name="com.example.student.RightFragment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="3"
tools:layout="@layout/fragment_right"
/>
</LinearLayout>
</LinearLayout>
两个Fragment布局代码
fragment_left.xml:
左侧导航栏的推荐与进店必买,最后效果中,需要点击这两个TextView来实现右侧导航栏数据的变化
<?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"
tools:context=".LeftFragment"
android:orientation="vertical">
<TextView
android:id="@+id/tv_recommend"
android:layout_width="100dp"
android:layout_height="40dp"
android:gravity="center"
android:textSize="12sp"
android:text="推荐" />
<TextView
android:id="@+id/tv_must_buy"
android:layout_width="100dp"
android:layout_height="40dp"
android:gravity="center"
android:textSize="12sp"
android:text="进店必买"/>
</LinearLayout>
fragment_right.xml:
Listview用于显示列表数据
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".RightFragment"
android:orientation="vertical">
<ListView
android:id="@+id/lv_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@null"
/>
</FrameLayout>
以及在fragment_right中LIstview的item布局:
list_item.xml
item中包含了一个ImageView用于显示食物图片信息,三个TextView显示食物标题、食物好评度、食物价格,同样的,其中子布局采用LinearLayout布局,并设置布局方向为垂直,使三个TextView垂直摆放
<?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"
android:padding="5dp">
<ImageView
android:id="@+id/iv_img"
android:layout_width="70dp"
android:layout_height="70dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:orientation="vertical"
>
<TextView
android:textSize="14sp"
android:padding="2dp"
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#868788"
android:id="@+id/tv_sale"
android:textSize="12sp"/>
<TextView
android:id="@+id/tv_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:textSize="12sp"/>
</LinearLayout>
</LinearLayout>
接下来是Java逻辑代码:
MainActivity.java:
在创建Activity生命周期中会执行onCreate()函数,在其中执行了setData、init、clickEvent方法,是三个自定义方法。setData方法:给数据赋值将其全部放在对应的数据集里,也就是添加两段ListVIew到时候现实的数据; init方法:给主页面左侧的fragment界面控件赋值(绑定控件),以及获得了管理Fragment的对象FragmentManager; clickEvent方法:生成左侧导航栏的点击事件,点击实现控件变化颜色,可以增加可适度。
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity52 extends AppCompatActivity {
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private Fragment leftFragment;
private RightFragment rightFragment;
private TextView tv_recommed,tv_must_buy;
private TextView btn;
private String[]names1={"爆款*肥牛鱼豆腐骨肉相连三荤五素一份米饭","豪华双人套餐","【热销】双人套餐(含两份米饭)"};
private String[]sales1={"月售520 好评度80%","月售520 好评度80%","月售520 好评度80%"};
private String[]prices1={"$23","$41","$32"};
private int []imgs1={R.drawable.recom_one,R.drawable.recom_two,R.drawable.recom_three};
private String[]names2={"素菜主义一人套餐","两人经典套套餐","三人经典套餐"};
private String[]sales2={"月售520 好评度80%","月售520 好评度80%","月售520 好评度80%"};
private String[]prices2={"$23","$41","$32"};
private int []imgs2={R.drawable.must_buy_one,R.drawable.must_buy_two,R.drawable.must_buy_three};
private Map<String, List<FoodsBean>>map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main52);
setData();
init();
clickEvent();
}
private void init(){//给主页面左侧的fragment界面控件赋值
fragmentManager = getFragmentManager();
leftFragment=fragmentManager.findFragmentById(R.id.left);
tv_recommed=findViewById(R.id.tv_recommend);
tv_must_buy=findViewById(R.id.tv_must_buy);
}
private void setData(){//给数据赋值将其全部放在对应的数据集里
map=new HashMap<>();
List<FoodsBean>list1=new ArrayList<>();
List<FoodsBean>list2=new ArrayList<>();
for(int i=0;i<names1.length;i++){
FoodsBean bean=new FoodsBean();
bean.setName(names1[i]);
bean.setPrice(prices1[i]);
bean.setImg(imgs1[i]);
bean.setSales(sales1[i]);
list1.add(bean);
}
map.put("1",list1);
for(int i=0;i<names2.length;i++){
FoodsBean bean=new FoodsBean();
bean.setName(names2[i]);
bean.setPrice(prices2[i]);
bean.setImg(imgs2[i]);
bean.setSales(sales2[i]);
list2.add(bean);
}
map.put("2",list2);
}
private void clickEvent(){//点击推荐还在必须控件变化颜色,可以增加可适度
tv_recommed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchData (map.get("1"));
tv_recommed.setBackgroundColor(Color.WHITE);
}
});
tv_must_buy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchData (map.get("2"));
tv_must_buy.setBackgroundColor(Color.WHITE);
}
});
switchData (map.get("1"));
}
public void switchData(List<FoodsBean> list){
rightFragment=new RightFragment().getInstance(list);//实例fragment
fragmentManager=getFragmentManager();//获取FragmentManager
fragmentTransaction=getSupportFragmentManager().beginTransaction();//开启事务
fragmentTransaction.replace(R.id.right,rightFragment);//添加一个Fragment
fragmentTransaction.commit();//提交事务
}
}
Food实体类FoodsBean:
实体类就不过多的讲述,毕竟是面向对象
import java.io.Serializable;
public class FoodsBean implements Serializable {
private static final long serialVersionUID=1L;
private String name;
private String sales;
private String price;
private int img;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSales() {
return sales;
}
public void setSales(String sales) {
this.sales = sales;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
}
Fragment其中LeftFragment的Java代码:
LeftFragment:
其实只重写onCreateView方法也可以。也就是绑定一下视图而已
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import org.jetbrains.annotations.NotNull;
public class LeftFragment extends Fragment {
@Override
public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@org.jetbrains.annotations.Nullable
@Override
public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_left,container,false);
return view;
}
@Override
public void onPause() {
super.onPause();
}
}
另一个RightFragment:
RightFragment:
因为要实现数据的切换以及Listview的数据显示,会比LeftFragment复杂一些
同样是重写一下方法。并写了一个构造方法用于设置数据,setArguments用于Activity与Fragment的通信,因为Activity、Fragment生命周期的一些问题,不能通过简单的数据传递
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import org.jetbrains.annotations.NotNull;
import java.io.Serializable;
import java.util.List;
public class RightFragment extends Fragment {
private ListView lv_list;
public RightFragment(){
}
public RightFragment getInstance(List<FoodsBean> list){
RightFragment rightFragment=new RightFragment();
Bundle bundle=new Bundle();
bundle.putSerializable("list", (Serializable) list);
rightFragment.setArguments(bundle);
return rightFragment;
}
@Override
public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@org.jetbrains.annotations.Nullable
@Override
public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_right,container,false);
lv_list=view.findViewById(R.id.lv_list);
if(getArguments()!=null){
List<FoodsBean> list= (List<FoodsBean>) getArguments().getSerializable("list");
RightAdapter adapter=new RightAdapter(getActivity(),list);
lv_list.setAdapter(adapter);
}
return view;
}
}
RightFargment中ListView的适配器代码:
RightAdapter:
适配器的作用是绑定数据与视图,在适配器中重写getCount、getItem、getItemId、getView方法,并为了复用ViewHolder,创建了一个内部类ViewHolder,其中list为存储了食物数据的列表,类型为List<FoodsBean>,getView为获取item的视图,并设置数据,其余重写的方法大体可以通过名字理解到意思,例如getCount意为item的个数,所以返回list的长度即可,调用size方法
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class RightAdapter extends BaseAdapter {
private Context mContext;
private List<FoodsBean>list;
public RightAdapter(Context context , List<FoodsBean>list){
this.mContext=context;
this.list=list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(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=View.inflate(mContext,R.layout.list_item,null);
holder= new ViewHolder();
holder.tv_name=convertView.findViewById(R.id.tv_name);
holder.tv_sale=convertView.findViewById(R.id.tv_sale);
holder.tv_price=convertView.findViewById(R.id.tv_price);
holder.iv_img=convertView.findViewById(R.id.iv_img);
convertView.setTag(holder);
}else {
holder=(ViewHolder) convertView.getTag();
}
FoodsBean bean=list.get(position);
holder.tv_name.setText(bean.getName());
holder.tv_sale.setText(bean.getSales());
holder.tv_price.setText(bean.getPrice());
holder.iv_img.setBackgroundResource(bean.getImg());
return convertView;
}
class ViewHolder{
TextView tv_name,tv_sale,tv_price;
ImageView iv_img;
}
}
简单的总结:
此次实验,学习的是Fragment为主要知识,从中贯穿了Listview的一个比较重要的知识点,界面分为了顶部导航栏、左侧菜单栏、右侧菜单栏,目前实验中顶部导航栏的切换功能还未实现,后续可以继续补充,左侧菜单栏做到了一个点击切换右侧菜单显示的内容的一个效果。Fragment英语单词意思是碎片。简单来说,Fragment其实可以理解为一个具有自己生命周期的控件,只不过这个控件又有点特殊,它有自己的处理输入事件的能力,有自己的生命周期,又必须依赖于Activity,能互相通信和托管。使用Fragment可以精简Activity文件的代码,便于更好的阅读,同时,有着更好的速度加载。