AppBarLayout效果:
当向下滑动屏幕是时 顶部就会出现
当向上滑动屏幕时 顶部就会折叠
向下滑动时: "
既然设置了ViewPager 那么我就需要几个Fragment碎片放进去
(实际有三个item 需要几个碎片就放几个item 我这里就给出一个做示范)
Item1:
接下来就到了Java代码的编写
Java代码:
先将fragment的类定义出来:
(需要几个fragment就写几个类,关联上对应的item布局)
Fragment1:
package org.wdan.test008;
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;
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//对应上我们的item1
View view=inflater.inflate(R.layout.item1,container,false);
return view;
}
}
Activity:
package org.wdan.test008;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
public class AppBarLayoutActivity extends AppCompatActivity {
private TabLayout tabs;
private AppBarLayout appbar;
private ViewPager viewPager;
//标题
String[] title={"新闻","财经","娱乐"};
List fragments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_bar_layout);
initView();
fragments.add(new Fragment1());
fragments.add(new Fragment2());
fragments.add(new Fragment3());
//通过适配器给viewPager添加碎片,我们通过内部类的方式在下面写了一个自定义适配器MyFragmentAdapter
viewPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(),fragments));
//关联viewPager与tablayout
tabs.setupWithViewPager(viewPager);
}
private void initView() {
fragments=new ArrayList();
tabs = (TabLayout) findViewById(R.id.tabs);
appbar = (AppBarLayout) findViewById(R.id.appbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
}
//自定义适配器
public class MyFragmentAdapter extends FragmentPagerAdapter {
List list;
public MyFragmentAdapter(FragmentManager fm,List list) {
super(fm);
this.list=list;
}
@Override
public Fragment getItem(int position) {
return list.get(position);
}
@Override
public int getCount() {
return list.size();
}
//这个方法可将标题对应上碎片
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
}
完成啦,快去运行看一看吧!
爱敲代码的小怪兽idan 原创文章 8获赞 3访问量 403 关注 私信 展开阅读全文作者:爱敲代码的小怪兽idan