一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 

安卓入门

七、ViewPager

1、ViewPager
  • layout1.xml、layout2.xml、layout3.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:background="#ffff0000"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="layout1"
        android:textSize="30sp" />

</LinearLayout>
  • activity_main.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">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
  • MyAdapter
public class MyAdapter extends PagerAdapter {
    private List<View> mListView;

    public MyAdapter(List<View> mListView) {
        this.mListView = mListView;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(mListView.get(position), 0);
        return mListView.get(position);
    }

    @Override
    public int getCount() {
        return mListView.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(mListView.get(position));
    }
}
  • MainActivity
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        LayoutInflater lf = getLayoutInflater().from(this);
        View view1 = lf.inflate(R.layout.layout1, null);
        View view2 = lf.inflate(R.layout.layout2, null);
        View view3 = lf.inflate(R.layout.layout3, null);

        ArrayList<View> viewList = new ArrayList<>();
        viewList.add(view1);
        viewList.add(view2);
        viewList.add(view3);

        ViewPager viewPager = findViewById(R.id.vp);
        MyAdapter myAdapter = new MyAdapter(viewList);
        viewPager.setAdapter(myAdapter);
        super.onCreate(savedInstanceState);
    }
}

八、Fragment

1、基本使用
  • BlankFragment
/**
 * ViewGroup:可以有子节点,布局、fragment控件继承
 * View:不可以有子节点,按钮、文本等基础控件继承
 */
public class BlankFragment extends Fragment {

    private View root;
    private TextView tv;
    private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (root == null) {
            root = inflater.inflate(R.layout.fragment_blank, container, false);
        }
        tv = root.findViewById(R.id.tv);
        btn = root.findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv.setText("世界");
            }
        });

        return root;
    }
}
  • fragment_blank.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">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="你好" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮" />

</LinearLayout>
  • activity_main.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">

    <fragment
        android:id="@+id/fg"
        android:name="com.wuxi.myandroid.BlankFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
2、动态添加Fragment
  • activity_main.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">

    <Button
        android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮1" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮2" />

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff00ffff" />

</LinearLayout>
  • MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        View btn1 = findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
        View btn2 = findViewById(R.id.btn2);
        btn2.setOnClickListener(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn1) {
            replaceFragment(new BlankFragment());
        } else if (v.getId() == R.id.btn2) {
            replaceFragment(new ItemFragment());
        }
    }

    /**
     * 动态添加Fragment步骤
     * 1)创建一个待处理的fragment
     * 2)获取FragmentManager,一般都是通过getSupportFragmentManager()
     * 3)开启一个事务transaction,一般调用fragmentManager的beginTransaction()
     * 4)使用transaction进行fragment的替换
     * 5)提交事务
     */
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //android.R.id.content:代表当前手机的窗体
        transaction.replace(R.id.fl, fragment);
        //添加到返回栈中
        transaction.addToBackStack(null);
        transaction.commit();
    }
}
3、Fragment与Fragment通信
  • MainActivity
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment1, new FirstFragment(), "fragment1");
        transaction.replace(R.id.fragment2, new SecondFragment(), "fragment2");
        transaction.addToBackStack(null);
        transaction.commit();
    }
}
  • FirstFragment
public class FirstFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        view.findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //与FragmentTransaction实例的replace方法参数3字符串对应
                SecondFragment fragment2 = (SecondFragment) getActivity().getFragmentManager().findFragmentByTag("fragment2");
                fragment2.setText("孟美岐");
            }
        });
        return view;
    }
}
  • SecondFragment
public class SecondFragment extends Fragment {
    private TextView tv;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second, container, false);
        tv = view.findViewById(R.id.tv);
        return view;
    }

    public void setText(String msg) {
        tv.setText(msg);
    }
}
4、Activity与Fragment通信
a、原生方案:Bundle
  • MainActivity
@Override
public void onClick(View v) {
    if (v.getId() == R.id.btn1) {
        Bundle bundle = new Bundle();
        bundle.putString("message", "这是一段中文");
        BlankFragment blankFragment = new BlankFragment();
        blankFragment.setArguments(bundle);
        replaceFragment(blankFragment);
    } else if (v.getId() == R.id.btn2) {
        replaceFragment(new ItemFragment());
    }
}
  • BlankFragment
@Override
public void onCreate(Bundle savedInstanceState) {
    Bundle bundle = getArguments();
    Log.d("BlankFragment", bundle.getString("message"));
    super.onCreate(savedInstanceState);
}
b、Java语言中类与类自己通信常用方案:接口
  • IFragmentCallback
public interface IFragmentCallback {
    void sendMsgToActivity(String msg);

    String getMsgFromActivity(String mag);
}
  • MainActivity
@Override
public void onClick(View v) {
    if (v.getId() == R.id.btn1) {
        BlankFragment blankFragment = new BlankFragment();
        blankFragment.setFragmentCallback(new IFragmentCallback() {
            @Override
            public void sendMsgToActivity(String msg) {
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public String getMsgFromActivity(String mag) {
                return "从activity获取信息";
            }
        });
        replaceFragment(blankFragment);
    } else if (v.getId() == R.id.btn2) {
        replaceFragment(new ItemFragment());
    }
}
  • BlankFragment
private IFragmentCallback fragmentCallback;

public void setFragmentCallback(IFragmentCallback fragmentCallback) {
    this.fragmentCallback = fragmentCallback;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (root == null) {
        root = inflater.inflate(R.layout.fragment_blank, container, false);
    }
    btn = root.findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // fragmentCallback.sendMsgToActivity("向activity发送信息");
            String msg = fragmentCallback.getMsgFromActivity("");
            Toast.makeText(BlankFragment.this.getContext(), msg, Toast.LENGTH_SHORT).show();
        }
    });
    return root;
}
c、其他方案:eventBus、LiveData
5、Fragment生命周期
a、activity和fragment生命周期对比
activity state fragment callbacks
Created onAttach()
Created onCreate()
Created onCreateView()
Created onActivityCreated()
Started onStart()
Resumed onResume()
Paused onPause()
Stopped onStop()
Destroyed onDestroyView()
Destroyed onDestroy()
Destroyed onDetach()
b、fragment生命周期总结
1、打开界面
    onCreate()->onCreateView()->onActivityCreated()->onStart()->onResume()

2、按下主屏键
    onPause()->onStop()

3、重新打开界面
    onStart()->onResume()

4、按后退键
    onPause()->onStop()->onDestroyView()->onDestroy()->onDetach()
6、fragment+viewPager滑动效果展示
a、viewPager2基本使用
  • build.gradle(:app)
dependencies {
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}
  • activity_main.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">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffd0d0d0" />

</LinearLayout>
  • item_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你好世界"
        android:textColor="#ffffffff"
        android:textSize="32sp" />

</LinearLayout>
  • MainActivity
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        ViewPager2 viewPager = findViewById(R.id.viewPager);
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter();
        viewPager.setAdapter(viewPagerAdapter);
        super.onCreate(savedInstanceState);
    }
}
  • ViewPagerAdapter
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolder> {
    private List<String> titles = new ArrayList<>();
    private List<Integer> colors = new ArrayList<>();

    public ViewPagerAdapter() {
        titles.add("黄婷婷");
        titles.add("孟美岐");
        titles.add("鞠婧祎");
        titles.add("佟丽娅");
        titles.add("程潇");
        colors.add(R.color.purple_200);
        colors.add(R.color.purple_500);
        colors.add(R.color.purple_700);
        colors.add(R.color.teal_200);
        colors.add(R.color.teal_700);
    }

    @NonNull
    @Override
    public ViewPagerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewPagerViewHolder holder, int position) {
        holder.container.setBackgroundResource(colors.get(position));
        holder.tv.setText(titles.get(position));
    }

    @Override
    public int getItemCount() {
        return 5;
    }

    class ViewPagerViewHolder extends RecyclerView.ViewHolder {
        TextView tv;
        LinearLayout container;

        public ViewPagerViewHolder(@NonNull View itemView) {
            super(itemView);
            container = itemView.findViewById(R.id.container);
            tv = itemView.findViewById(R.id.tv);
        }
    }
}
b、fragment与viewPager的联合使用
  • MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ViewPager2 viewPager;
    private LinearLayout llWeixin, llTongxunlu, llFaxian, llWode;
    private ImageView ivWeixin, ivTongxunlu, ivFaxian, ivWode, ivCurrent;

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

    private void initTabView() {
        llWeixin = findViewById(R.id.tab_weixin);
        llTongxunlu = findViewById(R.id.tab_tongxunlu);
        llFaxian = findViewById(R.id.tab_faxian);
        llWode = findViewById(R.id.tab_wode);
        llWeixin.setOnClickListener(this);
        llTongxunlu.setOnClickListener(this);
        llFaxian.setOnClickListener(this);
        llWode.setOnClickListener(this);

        ivWeixin = findViewById(R.id.tab_img_weixin);
        ivTongxunlu = findViewById(R.id.tab_img_tongxunlu);
        ivFaxian = findViewById(R.id.tab_img_faxian);
        ivWode = findViewById(R.id.tab_img_wode);

        ivWeixin.setSelected(true);
        ivCurrent = ivWeixin;
    }

    private void initPager() {
        viewPager = findViewById(R.id.viewPager);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(BlankFragment.newInstance("微信聊天"));
        fragments.add(BlankFragment.newInstance("通讯录"));
        fragments.add(BlankFragment.newInstance("发现"));
        fragments.add(BlankFragment.newInstance("我"));
        MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), getLifecycle(), fragments);
        viewPager.setAdapter(pagerAdapter);
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                changeTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
    }

    private void changeTab(int position) {
        ivCurrent.setSelected(false);
        switch (position) {
            case R.id.tab_weixin:
                viewPager.setCurrentItem(0);
            case 0:
                ivWeixin.setSelected(true);
                ivCurrent = ivWeixin;
                break;
            case R.id.tab_tongxunlu:
                viewPager.setCurrentItem(1);
            case 1:
                ivTongxunlu.setSelected(true);
                ivCurrent = ivTongxunlu;
                break;
            case R.id.tab_faxian:
                viewPager.setCurrentItem(2);
            case 2:
                ivFaxian.setSelected(true);
                ivCurrent = ivFaxian;
                break;
            case R.id.tab_wode:
                viewPager.setCurrentItem(3);
            case 3:
                ivWode.setSelected(true);
                ivCurrent = ivWode;
                break;
        }
    }

    @Override
    public void onClick(View v) {
        changeTab(v.getId());
    }
}
  • activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#ffd0d0d0" />

    <include layout="@layout/bottom_layout" />
</LinearLayout>
  • BlankFragment
public class BlankFragment extends Fragment {
    private static final String ARG_TEXT = "param1";

    private String mTextString;
    View rootView;

    public BlankFragment() {
    }

    public static BlankFragment newInstance(String param1) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_TEXT, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mTextString = getArguments().getString(ARG_TEXT);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_blank, container, false);
        }
        initView();
        return rootView;
    }

    private void initView() {
        TextView textView = rootView.findViewById(R.id.tv);
        textView.setText(mTextString);
    }
}
  • fragment_blank.xml
<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=".BlankFragment">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="@string/hello_blank_fragment"
        android:textSize="36sp" />

</FrameLayout>
  • MyFragmentPagerAdapter
public class MyFragmentPagerAdapter extends FragmentStateAdapter {
    List<Fragment> fragmentList = new ArrayList<>();

    public MyFragmentPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle, List<Fragment> fragments) {
        super(fragmentManager, lifecycle);
        fragmentList = fragments;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getItemCount() {
        return fragmentList.size();
    }
}
  • bottom_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/tab_weixin"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/tab_img_weixin"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:background="@drawable/tab_weixin" />

        <TextView
            android:id="@+id/tab_text_weixin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="微信" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tab_tongxunlu"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/tab_img_tongxunlu"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:background="@drawable/tab_tongxunlu" />

        <TextView
            android:id="@+id/tab_text_tongxunlu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="通讯录" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tab_faxian"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/tab_img_faxian"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:background="@drawable/tab_faxian" />

        <TextView
            android:id="@+id/tab_text_faxian"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发现" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tab_wode"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/tab_img_wode"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:background="@drawable/tab_wode" />

        <TextView
            android:id="@+id/tab_text_wode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我" />
    </LinearLayout>
</LinearLayout>
  • tab_weixin.xml、tab_tongxunlu.xml、tab_faxian.xml、tab_wode.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/weixin" android:state_selected="true" />
    <item android:drawable="@drawable/weixin_b" />
</selector>
posted on 2021-11-18 11:34  一路繁花似锦绣前程  阅读(34)  评论(0编辑  收藏  举报