智慧北京开发第一天(下)

完成引导页 & 进入主页

ViewPager监听事件,动态设置红点位置:

GuideActivity.java

package com.xbmu.wisdombj;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

public class GuideActivity extends Activity {
    private ViewPager vpGuide;
    private List<ImageView> imageViewList;//引导页的ImageView集合
    private LinearLayout llPointGroup;//点的集合
    private View viewRedPoint;

    private int pointSpace;//两点之间的间距

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);
        initViews();
    }

    /**
     * ViewPager的适配器
     */
    class GuideAdapter extends PagerAdapter {

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

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

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

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 初始化界面
     */
    private void initViews() {
        vpGuide = (ViewPager) findViewById(R.id.vp_guide);
        llPointGroup = (LinearLayout) findViewById(R.id.ll_point_group);
        viewRedPoint = findViewById(R.id.view_red_point);

        initDatas();

        //给ViewPager设置适配器
        vpGuide.setAdapter(new GuideAdapter());

        //measure(测量布局的大小) -> layout(在界面的位置) -> draw(绘画),这些方法只有在onCreate()方法执行完毕后,才会执行的逻辑。但是我们可以使用视图树解决这种问题。
        //获得视图树观察者,观察当整个布局的layout的事件
        viewRedPoint.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //此方法只需要执行一次就可以,把当前的监听事件从视图树中移除掉,以后就不会在回调此事件了
                viewRedPoint.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                //点的距离 = 第1个点的左边 - 第0个点的左边
                pointSpace = llPointGroup.getChildAt(1).getLeft() - llPointGroup.getChildAt(0).getLeft();
                System.out.println("两点之间的距离:" + pointSpace);

//                System.out.println("onGlobalLayout");

            }
        });

        //设置ViewPager页面切换变化的监听事件
        vpGuide.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            /**
             * 页面滑动监听
             * @param position 当前选中的位置
             * @param positionOffset 偏移百分比
             * @param positionOffsetPixels 页面偏移长度
             */
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                System.out.println("位置:" + position + ",位置移动的百分比:" + positionOffset + ",位置移动的像素:" + positionOffsetPixels);
                int leftMargin = (int) (pointSpace * positionOffset + pointSpace * position);
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) viewRedPoint.getLayoutParams();
                lp.leftMargin = leftMargin;
                viewRedPoint.setLayoutParams(lp);
            }

            //page页面被选中
            @Override
            public void onPageSelected(int position) {

            }

            //page页面滚动状态的变化
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //点的距离 = 第1个点的左边 - 第0个点的左边
        //pointSpace = llPointGroup.getChildAt(1).getLeft() - llPointGroup.getChildAt(0).getLeft();
        //System.out.println("两点之间的距离:" + pointSpace); //0
        // 这里获得的距离为0,是因为initView()方法是在onCreate()方法中调用,这时候界面还没有绘制出来,我们就去获取它在界面上的位置的时候,是获取不到的,肯定是有问题的。
    }

    private void initDatas() {
        imageViewList = new ArrayList<>(); //初始化引导页的3个页面 
        int[] idsImageView = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
        for (int i = 0; i < idsImageView.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(idsImageView[i]);//设置引导页背景 
            imageViewList.add(imageView); //初始化引导页的小圆点 
            View point = new View(this);
            point.setBackgroundResource(R.drawable.guide_point_shape);//设置引导页默认圆点 
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10, 10);//设置圆点的大小 
            if (i > 0) {
                params.leftMargin = 10;
            }
            llPointGroup.addView(point, params);//将圆点添加到线性布局中
        }
    }
}

运行效果:

滑动到最后一个页面,只显示"开始体验按钮"

GuideActivity.java

//page页面被选中
            @Override
            public void onPageSelected(int position) {
                if(position == imageViewList.size() - 1){//选中最后一个页面
                    btnStatr.setVisibility(View.VISIBLE);//显示"开始体验"按钮
                }else{
                    btnStatr.setVisibility(View.INVISIBLE);
                }

            }

使用SharedPreference保存参数,记录新手引导页面是否展示:

SharePreferenceUtils.java

package com.xbmu.wisdombj.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * 专门访问和设置SharePreference的工具类,保存和配置一些设置信息
 * Created by Administrator on 2016/2/4 0004.
 */
public class SharePreferenceUtils {
    private static final String SHARE_PREFS_NAME = "config";
    private static SharedPreferences mSharedPreferences;
    public static void putBoolean(Context ctx,String key,boolean value){
        if(mSharedPreferences == null){
            mSharedPreferences = ctx.getSharedPreferences(SHARE_PREFS_NAME,Context.MODE_PRIVATE);
        }
        mSharedPreferences.edit().putBoolean(key,value).commit();
    }
    public static Boolean getBoolean(Context ctx,String key,boolean defaultValue){
        if(mSharedPreferences == null){
            mSharedPreferences = ctx.getSharedPreferences(SHARE_PREFS_NAME,Context.MODE_PRIVATE);
        }
        return mSharedPreferences.getBoolean(key,defaultValue);
    }
}
GuideActivity.java
//设置"开始体验"按钮的监听事件
        btnStatr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //记录已经展示过新手引导页面
                SharePreferenceUtils.putBoolean(GuideActivity.this,"IS_USER_GUIDE_SHOWED",true);
                //跳转到主页面
                startActivity(new Intent(GuideActivity.this, MainActivity.class));
                finish();
            }
        });
SplashActivity.java
/**
             * 动画结束
             * @param animation
             */
            @Override
            public void onAnimationEnd(Animation animation) {
                //判断新手引导是否展示过
                boolean showed = SharePreferenceUtils.getBoolean(SplashActivity.this,"IS_USER_GUIDE_SHOWED",false);
                if(showed){
                    //展示过,跳转到主界面
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();//结束当前页面
                }else{
                    //没有展示过,跳转到引导界面
                    startActivity(new Intent(SplashActivity.this, GuideActivity.class));
                    finish();//结束当前页面
                }
            }
运行效果:

智慧北京开发第一天(下)_第1张图片

Library用法&SlidingMenu简介

下载SligdingMenu开源项目
直接拿来用!最火的Android开源项目

将下载好的SligdingMenu开源项目解压好之后,导入AndroidStudio中,参考方法如下:

AndroidStudio怎样导入library项目开源库

主要使用SlidingMenu项目中的侧滑菜单。

BaseFragment.java

package com.xbmu.wisdombj.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 基类BaseFragment,所有Fragment继承此类
 * 1.定义Activity常量,方便自类使用
 * 2.定义抽象方法initView() 初始化布局,必须实现
 * 3.定义方法initData(),初始化数据,可以不实现
 * Created by Administrator on 2016/2/4 0004.
 */
public abstract class BaseFragment extends Fragment {
    public Activity mActivity;
    //fragment创建
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
    }
    //处理fragment的布局
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = initView();
        return view;
    }

    /**
     * 初始化布局
     * @return
     */
    public abstract View initView();
    /**
     * Fragment所依赖的Activity创建完成
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 初始化数据
     */
    private void initData() {

    }

}
CotentFragment.java
package com.xbmu.wisdombj.fragment;

import android.view.View;
import com.xbmu.wisdombj.R;

/**
 * 主页面Fragment
 * Created by Administrator on 2016/2/4 0004.
 */
public class ContentFragment extends BaseFragment {
    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_content, null);
        return view;
    }
}

LeftMenuFragment.java

package com.xbmu.wisdombj.fragment;

import android.view.View;
import com.xbmu.wisdombj.R;

/**
 * 左侧菜单的Fragment
 * Created by Administrator on 2016/2/4 0004.
 */
public class LeftMenuFragment extends BaseFragment{
    @Override
    public View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_left_menu,null);
        return view;
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/fl_content"
    android:layout_height="match_parent">
</FrameLayout>

left_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/fl_left_menu"
    android:layout_height="match_parent">

</FrameLayout>
fragment_left_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#f00"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="侧滑菜单"/>
</RelativeLayout>
fragment_content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0f0">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是主页!"/>
</RelativeLayout>
MainActivity.java
package com.xbmu.wisdombj;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.xbmu.wisdombj.fragment.ContentFragment;
import com.xbmu.wisdombj.fragment.LeftMenuFragment;

/**
 * 主页面
 */
public class MainActivity extends SlidingFragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setBehindContentView(R.layout.left_menu);//设置侧边栏

        SlidingMenu slidingMenu = getSlidingMenu();//获取侧边栏对象

        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);//设置全屏触摸

        slidingMenu.setBehindOffset(200);//设置预留屏幕的宽度

        initFragment();
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        FragmentManager fm = getSupportFragmentManager();
        //开启事务
        FragmentTransaction ft = fm.beginTransaction();
        //替换帧布局
        ft.replace(R.id.fl_left_menu,new LeftMenuFragment());
        ft.replace(R.id.fl_content,new ContentFragment());

        //提交事务
        ft.commit();

    }

}



你可能感兴趣的:(智慧北京app)