viewpager 第一次启动导航页

以三个页面为例给大家介绍一下

第一步先新建三个XML布局文件

1,viewitem1.xml




2,viewitem2.xml




3,viewitem3.xml


    

布局文件建完之后,接着就是完成Activity中的代码,我在新增了一个导航页只显示一次的功能,首次进入app显示导航页,第二次进入导航页不显示。(红色的部分位导航页只显示一次)

public class DaoHangActivity extends AppCompatActivity {
    private Context context;
    private List viewList;
    private View view1,view2,view3;
    private ViewPager viewPager;
    private Button btnStart;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_dao_hang);
        context = this;
        sp = getSharedPreferences("SHOWONE",MODE_PRIVATE);
        final int one = sp.getInt("key",0);
        if (one == 1)
        {
            startActivity(new Intent(DaoHangActivity.this,LoginActivity.class));
        }
        viewPager = findViewById(R.id.viewpager);
        viewList = new ArrayList<>();
        LayoutInflater inflater = LayoutInflater.from(context);
        view1 = inflater.inflate(R.layout.viewitem1,null);
        view2 = inflater.inflate(R.layout.viewitem2,null);
        view3 = inflater.inflate(R.layout.viewitem3,null);
        viewList.add(view1);
        viewList.add(view2);
        viewList.add(view3);
        PagerAdapter adapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return viewList.size();
            }

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

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                View view = viewList.get(position);
                container.addView(view);
                return view;
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(viewList.get(position));
            }
        };
        viewPager.setAdapter(adapter);
        btnStart = view3.findViewById(R.id.btn_startApp);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editor = sp.edit();
                if(one==0)
                {
                    editor.putInt("key",1);
                    startActivity(new Intent(DaoHangActivity.this,LoginActivity.class));
                    editor.commit();
                }

            }
        });
    }
}

你可能感兴趣的:(viewpager 第一次启动导航页)