このコースのテーマはフラグメントです. コースの例は Meituan のテイクアウト インターフェイスを模倣しています, これは下部ナビゲーション バーのフラグメントの場合とは異なります. このインターフェイスは左側のスイッチングと上部のスイッチングに分かれています。この記事ではまずコードとエフェクトを公開し、その後の説明は後ほど追加します。まずは効果を見てみましょう:
1 つ目はレイアウト ファイルのコードです: アクティビティ レイアウト: activity_main.xml:
まず、親レイアウトに LinearLayout レイアウトを使用し、コード android:orientation="vertical" を使用してレイアウト方向を垂直レイアウトに設定します。インターフェイスは上部のナビゲーション バー、左側のメニュー バー、右側のメニュー バーに分かれており、さらに 3 つの主要なサブレイアウトに分かれています。
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>
2 つのフラグメント レイアウト コード
フラグメント_左.xml:
左側のナビゲーション バーの推奨事項と、ストアに入るときに必ず購入するもの。最終的には、これら 2 つの 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>
フラグメント右.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 の項目レイアウト:
list_item.xml
このアイテムには、食品の写真情報を表示する ImageView と、食品のタイトル、食品の評価、および食品の価格を表示する 3 つの TextView が含まれています。同様に、サブレイアウトは LinearLayout レイアウトを採用し、レイアウトの方向を垂直に設定して、3 つのビューが表示されるようにします。 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:
onCreate() 関数は、Activity ライフサイクルの作成中に実行され、そこで setData、init、clickEvent メソッド (3 つのカスタム メソッド) が実行されます。 setData メソッド: データに値を割り当て、それらをすべて対応するデータ セットに配置します。つまり、ListVIew の 2 つのセクションを実際のデータに追加します。init メソッド: 左側のフラグメント インターフェイス コントロールに値を割り当てます 。メインページ(バインドコントロール)を取得し、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();//提交事务
}
}
食品エンティティ クラス 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 コード:
左フラグメント:
実は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 :
右フラグメント:
データ切り替えや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 のアダプター コード:
右アダプター:
アダプターの役割は、データとビューをバインドし、アダプター内の getCount、getItem、getItemId、および getView メソッドを書き換え、ViewHolder を再利用するために内部クラス ViewHolder を作成することです。list は食品データを保存するリストです。型は List <FoodsBean>、getView は項目のビューの取得とデータの設定です。残りのオーバーライドされたメソッドは名前から大まかに理解できます。たとえば、getCount は項目の数を意味するため、単にリストの長さを指定して 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 は独自のライフ サイクルを持つコントロールとして理解できますが、このコントロールは少し特殊で、入力イベントを処理する独自の機能、独自のライフ サイクルを持ち、通信するにはアクティビティに依存する必要があります。お互いに、そしてホスティングをします。フラグメントを使用すると、アクティビティ ファイルのコードが簡素化され、読みやすくなり、同時に読み込み速度も向上します。