A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 小鲁哥哥 于 2017-4-20 15:12 编辑

【济南中心】Android课程同步笔记Day2:智慧北京-项目实现

Splash界面动画


效果分析:
全屏显示
执行旋转、缩放、透明度改变动画
       动画执行完成后,进入引导界面

文件AndroidManifest.xml:
[XML] 纯文本查看 复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.zhbj">

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon_150"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.SplashActivity"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
           >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activity.GuideActivity"/>
        <activity android:name=".activity.MainActivity"
            android:theme="@android:style/Theme.NoTitleBar"/>
    </application>

</manifest>

执行动画
[Java] 纯文本查看 复制代码
package com.itheima.zhbj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.RelativeLayout;

import com.itheima.zhbj.R;
import com.itheima.zhbj.utils.Constant;
import com.itheima.zhbj.utils.SPUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SplashActivity extends Activity implements Animation.AnimationListener {

    @BindView(R.id.rl)
    RelativeLayout rl;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

        Animation animation = createAnimation();
        rl.startAnimation(animation);
        //监听动画
        animation.setAnimationListener(this);
    }

    //创建动画
    private Animation createAnimation(){
        AnimationSet set = new AnimationSet(false);
        //旋转
        RotateAnimation rotate = new RotateAnimation(0,360,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        rotate.setDuration(2000);
        //缩放
        ScaleAnimation scale = new ScaleAnimation(0,1,0,1,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        scale.setDuration(2000);
        //透明度
        AlphaAnimation alpha = new AlphaAnimation(0,1);
        alpha.setDuration(1000);

        set.addAnimation(rotate);
        set.addAnimation(scale);
        set.addAnimation(alpha);
        return set;
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    //动画执行后调用
    @Override
    public void onAnimationEnd(Animation animation) {
        //延时2s进入向导界面GuideActivity  该方法在主线程   发送一个延时的消息
        mHandler.postDelayed(new MyTask(),2000);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    private class MyTask implements  Runnable{

        @Override
        public void run() {
           boolean has_guide =  SPUtils.getBoolean(getApplicationContext(), Constant.KEY_HAS_GUIDE,false);
            if(has_guide){
                //进入主界面
                Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(intent);
            }else{
                //进入向导界面
                Intent intent = new Intent(getApplicationContext(),GuideActivity.class);
                startActivity(intent);
            }
            finish();
        }
    }
}

添加动画监听,执行跳转
[Java] 纯文本查看 复制代码
package com.itheima.zhbj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.RelativeLayout;

import com.itheima.zhbj.R;
import com.itheima.zhbj.utils.Constant;
import com.itheima.zhbj.utils.SPUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SplashActivity extends Activity implements Animation.AnimationListener {

    @BindView(R.id.rl)
    RelativeLayout rl;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

        Animation animation = createAnimation();
        rl.startAnimation(animation);
        //监听动画
        animation.setAnimationListener(this);
    }

    //创建动画
    private Animation createAnimation(){
        AnimationSet set = new AnimationSet(false);
        //旋转
        RotateAnimation rotate = new RotateAnimation(0,360,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        rotate.setDuration(2000);
        //缩放
        ScaleAnimation scale = new ScaleAnimation(0,1,0,1,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
        scale.setDuration(2000);
        //透明度
        AlphaAnimation alpha = new AlphaAnimation(0,1);
        alpha.setDuration(1000);

        set.addAnimation(rotate);
        set.addAnimation(scale);
        set.addAnimation(alpha);
        return set;
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    //动画执行后调用
    @Override
    public void onAnimationEnd(Animation animation) {
        //延时2s进入向导界面GuideActivity  该方法在主线程   发送一个延时的消息
        mHandler.postDelayed(new MyTask(),2000);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    private class MyTask implements  Runnable{

        @Override
        public void run() {
           boolean has_guide =  SPUtils.getBoolean(getApplicationContext(), Constant.KEY_HAS_GUIDE,false);
            if(has_guide){
                //进入主界面
                Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(intent);
            }else{
                //进入向导界面
                Intent intent = new Intent(getApplicationContext(),GuideActivity.class);
                startActivity(intent);
            }
            finish();
        }
    }
}

向导界面的ViewPager

打开【文件activity_guide.xml】,引入Viewpager控件
[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.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v4.view.ViewPager>

</RelativeLayout>

去除标题和状态栏
[Java] 纯文本查看 复制代码
public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "GuideActivity";
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.bt_start)
    Button btStart;
    @BindView(R.id.red_point)
    View redPoint;
    @BindView(R.id.container_gray_point)
    LinearLayout containerGrayPoint;
    //向导图片
    private int[] imgs = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private List<ImageView> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

}

初始化ViewPager和数据,动态创建图片
[Java] 纯文本查看 复制代码
public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "GuideActivity";
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.bt_start)
    Button btStart;
    @BindView(R.id.red_point)
    View redPoint;
    @BindView(R.id.container_gray_point)
    LinearLayout containerGrayPoint;
    //向导图片
    private int[] imgs = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private List<ImageView> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initViewPager();

    }


    //初始化ViewPager的数据
    private void initViewPager() {
        views = new ArrayList<>();
        for (int resId : imgs) {
            ImageView iv = new ImageView(this);
            iv.setBackgroundResource(resId);
            views.add(iv);
        }

      }
}

创建适配器,加载图片
[Java] 纯文本查看 复制代码
public class GuideVPAdapter extends PagerAdapter {

    private List<ImageView> views;

    public GuideVPAdapter(List<ImageView> views) {
        this.views = views;
    }

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

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

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

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

绑定Viewpager
[Java] 纯文本查看 复制代码
package com.itheima.zhbj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "GuideActivity";
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.bt_start)
    Button btStart;
    @BindView(R.id.red_point)
    View redPoint;
    @BindView(R.id.container_gray_point)
    LinearLayout containerGrayPoint;
    //向导图片
    private int[] imgs = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private List<ImageView> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initViewPager();
        initGrayPoint();
    }

    //动态的创建灰色的点
    private void initGrayPoint() {
        for (int resId : imgs) {
            View view = new View(this);
            view.setBackgroundResource(R.drawable.point_gray_bg);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10,10);
            params.rightMargin = 20;//设置右边距
            containerGrayPoint.addView(view,params);
        }
    }

    //初始化ViewPager的数据
    private void initViewPager() {
        views = new ArrayList<>();
        for (int resId : imgs) {
            ImageView iv = new ImageView(this);
            iv.setBackgroundResource(resId);
            views.add(iv);
        }

        vp.setAdapter(new GuideVPAdapter(views));
    }
}

开始体验按钮

在布局中添加开始体验按钮
[Java] 纯文本查看 复制代码
<?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.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v4.view.ViewPager>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始体验"
        android:id="@+id/bt_start"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="60dp"
        android:visibility="gone"
        android:padding="15dp"
        android:textColor="@color/btn_text_selector"
        android:background="@drawable/btn_selector"/>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp">

        <LinearLayout
            android:id="@+id/container_gray_point"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <!--在代码中动态的添加灰色的点-->
        </LinearLayout>
        <!--红色的点-->
        <View
            android:id="@+id/red_point"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:background="@drawable/point_red_bg"/>
    </RelativeLayout>


</RelativeLayout>

给ViewPager添加滑动监听
[Java] 纯文本查看 复制代码
public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "GuideActivity";
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.bt_start)
    Button btStart;
    @BindView(R.id.red_point)
    View redPoint;
    @BindView(R.id.container_gray_point)
    LinearLayout containerGrayPoint;
    //向导图片
    private int[] imgs = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private List<ImageView> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initViewPager();
   
    }

      //初始化ViewPager的数据
    private void initViewPager() {
        views = new ArrayList<>();
        for (int resId : imgs) {
            ImageView iv = new ImageView(this);
            iv.setBackgroundResource(resId);
            views.add(iv);
        }

        vp.setAdapter(new GuideVPAdapter(views));
        //设置页面的滑动监听
        vp.addOnPageChangeListener(this);
    }




    //position:当前滑动页面的下标    positionOffset:页面的滑动比率    positionOffsetPixels:页面滑动的实际像素
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
      
    }

    //页面选中的时候调用
    @Override
    public void onPageSelected(int position) {
        if (position == imgs.length - 1) {
            //显示按钮
            btStart.setVisibility(View.VISIBLE);
        } else {
            //隐藏按钮
            btStart.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

处理ViewPager监听事件
[Java] 纯文本查看 复制代码
/**
 * Created by Apple on 2016/9/23.
 */
public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "GuideActivity";
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.bt_start)
    Button btStart;
    @BindView(R.id.red_point)
    View redPoint;
    @BindView(R.id.container_gray_point)
    LinearLayout containerGrayPoint;
    //向导图片
    private int[] imgs = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private List<ImageView> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initViewPager();

    }

        //初始化ViewPager的数据
    private void initViewPager() {
        views = new ArrayList<>();
        for (int resId : imgs) {
            ImageView iv = new ImageView(this);
            iv.setBackgroundResource(resId);
            views.add(iv);
        }

        vp.setAdapter(new GuideVPAdapter(views));
        //设置页面的滑动监听
        vp.addOnPageChangeListener(this);
    }

    @OnClick(R.id.bt_start)
    public void onClick() {
        //进入主界面
        SPUtils.saveBoolean(this, Constant.KEY_HAS_GUIDE,true);
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    //页面选中的时候调用
    @Override
    public void onPageSelected(int position) {
        if (position == imgs.length - 1) {
            //显示按钮
            btStart.setVisibility(View.VISIBLE);
        } else {
            //隐藏按钮
            btStart.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

给开始按钮添加点击事件
[Java] 纯文本查看 复制代码
public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "GuideActivity";
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.bt_start)
    Button btStart;
    @BindView(R.id.red_point)
    View redPoint;
    @BindView(R.id.container_gray_point)
    LinearLayout containerGrayPoint;
    //向导图片
    private int[] imgs = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private List<ImageView> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initViewPager();
        initGrayPoint();
    }

    //动态的创建灰色的点
    private void initGrayPoint() {
        for (int resId : imgs) {
            View view = new View(this);
            view.setBackgroundResource(R.drawable.point_gray_bg);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10,10);
            params.rightMargin = 20;//设置右边距
            containerGrayPoint.addView(view,params);
        }
    }

    //初始化ViewPager的数据
    private void initViewPager() {
        views = new ArrayList<>();
        for (int resId : imgs) {
            ImageView iv = new ImageView(this);
            iv.setBackgroundResource(resId);
            views.add(iv);
        }

        vp.setAdapter(new GuideVPAdapter(views));
        //设置页面的滑动监听
        vp.addOnPageChangeListener(this);
    }

    @OnClick(R.id.bt_start)
    public void onClick() {
        //进入主界面
        SPUtils.saveBoolean(this, Constant.KEY_HAS_GUIDE,true);
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    }



    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    //页面选中的时候调用
    @Override
    public void onPageSelected(int position) {
        if (position == imgs.length - 1) {
            //显示按钮
            btStart.setVisibility(View.VISIBLE);
        } else {
            //隐藏按钮
            btStart.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

开始按钮添加状态选择器
[XML] 纯文本查看 复制代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true" android:drawable="@drawable/button_red_pressed"/>
    <item android:drawable="@drawable/button_red_normal"/>

</selector>

给按钮添加文字颜色选择器
[XML] 纯文本查看 复制代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="#000"/>
    <item android:color="#fff"/>
</selector>
设置状态选择器
[Java] 纯文本查看 复制代码
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="开始体验"
    android:id="@+id/bt_start"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="60dp"
    android:visibility="gone"
    android:padding="15dp"
    android:textColor="@color/btn_text_selector"
    android:background="@drawable/btn_selector"/>
创建红色和灰色的小圆点

添加布局
[XML] 纯文本查看 复制代码
<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp">

        <LinearLayout
            android:id="@+id/container_gray_point"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <!--在代码中动态的添加灰色的点-->
        </LinearLayout>
        <!--红色的点-->
        <View
            android:id="@+id/red_point"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:background="@drawable/point_red_bg"/>
    </RelativeLayout>

初始化小灰点
[Java] 纯文本查看 复制代码
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //去除标题
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_guide);
    ButterKnife.bind(this);
    //去除状态栏
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    initViewPager();
    initGrayPoint();
}

//动态的创建灰色的点
private void initGrayPoint() {
    for (int resId : imgs) {
        View view = new View(this);
        view.setBackgroundResource(R.drawable.point_gray_bg);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10,10);
        params.rightMargin = 20;//设置右边距
        containerGrayPoint.addView(view,params);
    }
}

小红点的移动
小红点移动原理:
1. 获取第一个小灰点的左边距离
              containerGrayPoint.getChildAt(0).getLeft()
2. 获取第二个小灰点的左边距离
              containerGrayPoint.getChildAt(1).getLeft()
3.两点之间的距离 = 第二点的左边距离 - 第一个点的左边距离
              containerGrayPoint.getChildAt(1).getLeft()-llContainer.getChildAt(0).getLeft();
4. 根据移动的百分百,计算小红点当前移动之后的左边距
根据当前的ViewPager移动的索引*小红点移动的距离 + 小红点移动距离 * 滑动百分比
设置ViewPager的滑动监听
[Java] 纯文本查看 复制代码
public class GuideActivity extends Activity implements ViewPager.OnPageChangeListener {

    private static final String TAG = "GuideActivity";
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.bt_start)
    Button btStart;
    @BindView(R.id.red_point)
    View redPoint;
    @BindView(R.id.container_gray_point)
    LinearLayout containerGrayPoint;
    //向导图片
    private int[] imgs = new int[]{R.drawable.guide_1, R.drawable.guide_2, R.drawable.guide_3};
    private List<ImageView> views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_guide);
        ButterKnife.bind(this);
        //去除状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        initViewPager();
        initGrayPoint();
    }

    //动态的创建灰色的点
    private void initGrayPoint() {
        for (int resId : imgs) {
            View view = new View(this);
            view.setBackgroundResource(R.drawable.point_gray_bg);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(10,10);
            params.rightMargin = 20;//设置右边距
            containerGrayPoint.addView(view,params);
        }
    }

    //初始化ViewPager的数据
    private void initViewPager() {
        views = new ArrayList<>();
        for (int resId : imgs) {
            ImageView iv = new ImageView(this);
            iv.setBackgroundResource(resId);
            views.add(iv);
        }

        vp.setAdapter(new GuideVPAdapter(views));
        //设置页面的滑动监听
        vp.addOnPageChangeListener(this);
    }

    @OnClick(R.id.bt_start)
    public void onClick() {
        //进入主界面
        SPUtils.saveBoolean(this, Constant.KEY_HAS_GUIDE,true);
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    }

    //小灰点之间的宽度
    private int width;

    //position:当前滑动页面的下标    positionOffset:页面的滑动比率    positionOffsetPixels:页面滑动的实际像素
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        MyLogger.i(TAG,"position:"+position+",positionOffset:"+positionOffset+",positionOffsetPixels:"+positionOffsetPixels);

        if(width == 0){
            width = containerGrayPoint.getChildAt(1).getLeft() - containerGrayPoint.getChildAt(0).getLeft();
            MyLogger.i(TAG,"width:"+width);
        }

        //修改小红点与相对布局的左边距
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) redPoint.getLayoutParams();
        params.leftMargin = (int)(position*width + width*positionOffset);
        redPoint.setLayoutParams(params);
    }

    //页面选中的时候调用
    @Override
    public void onPageSelected(int position) {
        if (position == imgs.length - 1) {
            //显示按钮
            btStart.setVisibility(View.VISIBLE);
        } else {
            //隐藏按钮
            btStart.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
监听onPageScrolled方法,移动小圆点
[Java] 纯文本查看 复制代码
//position:当前滑动页面的下标    positionOffset:页面的滑动比率    positionOffsetPixels:页面滑动的实际像素
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    MyLogger.i(TAG,"position:"+position+",positionOffset:"+positionOffset+",positionOffsetPixels:"+positionOffsetPixels);

    if(width == 0){
        width = containerGrayPoint.getChildAt(1).getLeft() - containerGrayPoint.getChildAt(0).getLeft();
        MyLogger.i(TAG,"width:"+width);
    }

    //修改小红点与相对布局的左边距
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) redPoint.getLayoutParams();
    params.leftMargin = (int)(position*width + width*positionOffset);
    redPoint.setLayoutParams(params);
}
通过首选项记录是否体验过向导、进入主界面
封装sp工具
[Java] 纯文本查看 复制代码
public final class SPUtils {
   
   private final static String name = "config";
   private final static int mode = Context.MODE_PRIVATE;
   
   /**
    * 保存首选项
    * @param context
    * @param key
    * @param value
    */
   public static void saveBoolean(Context context,String key,boolean value){
      SharedPreferences sp = context.getSharedPreferences(name, mode);
      Editor edit = sp.edit();
      edit.putBoolean(key, value);
      edit.commit();
   }
   public static void saveInt(Context context,String key,int value){
      SharedPreferences sp = context.getSharedPreferences(name, mode);
      Editor edit = sp.edit();
      edit.putInt(key, value);
      edit.commit();
   }
   public static void saveString(Context context,String key,String value){
      SharedPreferences sp = context.getSharedPreferences(name, mode);
      Editor edit = sp.edit();
      edit.putString(key, value);
      edit.commit();
   }
   
   
   /**
    * 获取首选项
    * @param context
    * @param key
    * @param defValue
    * @return
    */
   public static boolean getBoolean(Context context,String key,boolean defValue){
      SharedPreferences sp = context.getSharedPreferences(name, mode);
      return sp.getBoolean(key, defValue);
   }
   
   public static int getInt(Context context,String key,int defValue){
      SharedPreferences sp = context.getSharedPreferences(name, mode);
      return sp.getInt(key, defValue);
   }
   
   public static String getString(Context context,String key,String defValue){
      SharedPreferences sp = context.getSharedPreferences(name, mode);
      return sp.getString(key, defValue);
   }

}
记录开启向导界面
[Java] 纯文本查看 复制代码
@onClick(R.id.btn_start)
        public  void onClick() {
                SPUtil.saveBoolean(this,Constant.KEY_HAS_GUIDE,true);
                Intent intent =new Intent(this ,MainActivity.class);
                startActivity(intent);
                finish();
        }
在闪屏界面,动画结束之后,根据记录的首选项,跳转界面

底部tab的实现
布局文件
[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"
   >

    <com.itheima.zhbj.view.NoScrollViewPager
        android:id="@+id/tab_vp"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <RadioGroup
        android:id="@+id/rg_tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/bottom_tab_bg"
        android:gravity="center_vertical"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/rb_home"
            android:drawableTop="@drawable/tab_home_selector"
            android:text="首页"
            android:checked="true"
            style="@style/main_tab_rg_style" />
        <RadioButton
            android:id="@+id/rb_newscener"
            android:drawableTop="@drawable/tab_newscenter_selector"
            android:text="新闻中心"
            style="@style/main_tab_rg_style" />
        <RadioButton
            android:id="@+id/rb_smartservice"
            android:drawableTop="@drawable/tab_smartservice_selector"
            android:text="智慧服务"
            style="@style/main_tab_rg_style" />
        <RadioButton
            android:id="@+id/rb_govaffairs"
            android:drawableTop="@drawable/tab_govaffairs_selector"
            android:text="政务"
            style="@style/main_tab_rg_style" />
        <RadioButton
            android:id="@+id/rb_setting"
            android:drawableTop="@drawable/tab_setting_selector"
            android:text="设置"
            style="@style/main_tab_rg_style" />
    </RadioGroup>

</LinearLayout>
抽取RadioButton相同样式
为每个底部tab添加图片选择器(以tab_home_selector为例)
为每个tab的文字添加颜色选择器(以tab_home_selector为例)

ViewPager+Fragment+FragmentViewPager的实现
布局初始化

初始化ViewPpager

创建5个Fragment(以homeFragment为例)


创建FragmentPagerAdapter,初始化5个Fragment
ViewPager绑定5个Fragment



点击底部的tab切换ViewPager的页面给RadioGrou设置滑动监听

实现onCheckedChanagerListener的回调方法:监听选中事件

让ViewPager切换到对应的Fragment

侧滑菜单的引入
创建侧滑菜单布局
[Java] 纯文本查看 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0f0">

</LinearLayout>

初始化侧滑菜单
[Java] 纯文本查看 复制代码
//初始化侧滑菜单
private void initSlidingMenu() {
    //创建侧滑菜单对象
    slidingMenu = new SlidingMenu(this);
    //设置菜单从左边滑出
    slidingMenu.setMode(SlidingMenu.LEFT);
    //设置侧滑菜单,默认不可以滑出
    slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
    //设置侧滑菜单滑出后,主界面的宽度
    slidingMenu.setBehindOffset(200);
    //以内容的形式添加到Activity
    slidingMenu.attachToActivity(this,SlidingMenu.SLIDING_CONTENT);
    //设置侧滑菜单的布局
    slidingMenu.setMenu(R.layout.activity_main_menu);


禁用ViewPager左右滑动
自定义ViewPager处理拦截事件和处理事件,不对此滑动事件进行拦截,不对此滑动事件处理
[Java] 纯文本查看 复制代码
public class NoScrollViewPager extends ViewPager {
    public NoScrollViewPager(Context context) {
        super(context);
    }

    public NoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;//不拦击事件
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return false;//不处理事件
    }
}

替换V4包的ViewPager


BaseFragment布局的抽取
初始化布局文件

[Java] 纯文本查看 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:background="#fff"
    android:layout_height="match_parent">
    <!--标题-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/title_red_bg">
        <ImageButton
            android:id="@+id/ib_menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/img_menu"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"/>
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#fff"
            android:textSize="18sp"
            android:text="标题"
            />
        <ImageButton
            android:id="@+id/ib_pic_type"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/icon_pic_grid_type"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp"
            android:layout_alignParentRight="true"/>
    </RelativeLayout>
    <!--内容-->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></FrameLayout>
</LinearLayout>
BaseFragment标题的抽取

[Java] 纯文本查看 复制代码
public abstract class BaseFragment extends Fragment {

    @BindView(R.id.ib_menu)
    ImageButton ibMenu;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ib_pic_type)
    ImageButton ibPicType;
    @BindView(R.id.container)
    FrameLayout container;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab_base, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTitle();
    }

    //初始化标题   让每个子类去进行实现
    public abstract void initTitle();

    //设置Menu的显示状态
    public void setIbMenuDisplayState(boolean isShow){
        ibMenu.setVisibility(isShow?View.VISIBLE:View.GONE);
    }
    //设置PicType的显示状态
    public void setIbPicTypeDisplayState(boolean isShow){
        ibPicType.setVisibility(isShow?View.VISIBLE:View.GONE);
    }

    //设置标题内容
    public void setTitle(String title){
        tvTitle.setText(title);
    }

    //创建内容
    public abstract View createContent();

    //向容器里面添加内容
    public void addView(View view){
        //清空原来的内容
        container.removeAllViews();
        //添加内容
        container.addView(view);
    }


    @OnClick(R.id.ib_menu)
    public void onClick() {
        //对于侧滑菜单进行切换
        //目标:获取SlidingMenu -->MainActivity
        ((MainActivity)getActivity()).slidingMenu.toggle();
    }
}

BaseFragment内容的抽取

[Java] 纯文本查看 复制代码
public abstract class BaseFragment extends Fragment {

    @BindView(R.id.ib_menu)
    ImageButton ibMenu;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ib_pic_type)
    ImageButton ibPicType;
    @BindView(R.id.container)
    FrameLayout container;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab_base, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTitle();
    }

    //初始化标题   让每个子类去进行实现
    public abstract void initTitle();

    //设置Menu的显示状态
    public void setIbMenuDisplayState(boolean isShow){
        ibMenu.setVisibility(isShow?View.VISIBLE:View.GONE);
    }
    //设置PicType的显示状态
    public void setIbPicTypeDisplayState(boolean isShow){
        ibPicType.setVisibility(isShow?View.VISIBLE:View.GONE);
    }

    //设置标题内容
    public void setTitle(String title){
        tvTitle.setText(title);
    }

    //创建内容
    public abstract View createContent();

    //向容器里面添加内容
    public void addView(View view){
        //清空原来的内容
        container.removeAllViews();
        //添加内容
        container.addView(view);
    }

}

定义向容器添加内容的方法
[Java] 纯文本查看 复制代码
public abstract class BaseFragment extends Fragment {

    @BindView(R.id.ib_menu)
    ImageButton ibMenu;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ib_pic_type)
    ImageButton ibPicType;
    @BindView(R.id.container)
    FrameLayout container;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab_base, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initTitle();
    }

    //初始化标题   让每个子类去进行实现
    public abstract void initTitle();

    //设置Menu的显示状态
    public void setIbMenuDisplayState(boolean isShow){
        ibMenu.setVisibility(isShow?View.VISIBLE:View.GONE);
    }
    //设置PicType的显示状态
    public void setIbPicTypeDisplayState(boolean isShow){
        ibPicType.setVisibility(isShow?View.VISIBLE:View.GONE);
    }

    //设置标题内容
    public void setTitle(String title){
        tvTitle.setText(title);
    }

    //创建内容
    public abstract View createContent();

    //向容器里面添加内容
    public void addView(View view){
        //清空原来的内容
        container.removeAllViews();
        //添加内容
        container.addView(view);
    }


    @OnClick(R.id.ib_menu)
    public void onClick() {
        //对于侧滑菜单进行切换
        //目标:获取SlidingMenu -->MainActivity
        ((MainActivity)getActivity()).slidingMenu.toggle();
    }
}

联网获取数据接口抽取

五个Fragment中,由于首页、新闻中心、智慧服务、政务
需要联网的,因此 抽取一个联网加载数据的行为,定义个联网加载数据的接口。
[Java] 纯文本查看 复制代码
interface BaseLoadNetDataOperator{
       public void loadNetData(String url);
}
让首页、新闻中心、智慧服务、政务去实现。
代码实现

点击menu完成侧滑菜单的切换

给菜单按钮添加点击事件
[Java] 纯文本查看 复制代码
@OnClick(R.id.ib_menu)
public void onClick() {
    //对于侧滑菜单进行切换
    //目标:获取SlidingMenu -->MainActivity
    ((MainActivity)getActivity()).slidingMenu.toggle();
}

控制SlidingMenu的打开和关闭
[Java] 纯文本查看 复制代码
@OnClick(R.id.ib_menu)
public void onClick() {
    //对于侧滑菜单进行切换
    //目标:获取SlidingMenu -->MainActivity
    ((MainActivity)getActivity()).slidingMenu.toggle();
}

不同的Tab页面控制侧滑菜单是否可以滑出
tab切换时,控制slidingMenu的滑出模式

设置SlindingMenu默认不可滑动
注意:这是tab切换时,来控制滑动模式。默认情况下,slidingMenu的滑动模式为可滑出的。因此,在初始化SlindingMenu时,设置默认的不可滑出


加载数据的入口
切换Fragment,联网获取数据
[Java] 纯文本查看 复制代码
public void onCheckedChanged(RadioGroup group, int checkedId) {
    int item = 0;
    switch (checkedId){
        case R.id.rb_home:
            item = 0;
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);//无法滑出侧滑菜单
            break;
        case R.id.rb_newscener:
            item = 1;
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
            break;
        case R.id.rb_smartservice:
            item = 2;
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
            break;
        case R.id.rb_govaffairs:
            item = 3;
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
            break;
        case R.id.rb_setting:
            item = 4;
            slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
            break;
    }
    //让上面的ViewPager切换到对应的页面
    tabVp.setCurrentItem(item,false);

    //加载网络数据的入口
    BaseFragment baseFragment = (BaseFragment) fragments.get(item);
    if(baseFragment instanceof BaseLoadNetDataOperator){
        ((BaseLoadNetDataOperator) baseFragment).loadNetData();
    }
}

从服务器上获取新闻中心页的数据
定义常量类
[Java] 纯文本查看 复制代码
public class Constant {

    //是否已经执行完向导
    public final static String KEY_HAS_GUIDE = "key_has_guide";
    //服务器的主机
    public final static String HOST = "http://10.0.2.2:8080/zhbj";

    //新闻中心页面的数据地址
    public final static String NEWSCENTER_URL = HOST + "/categories.json";
}

网络加载数据
[Java] 纯文本查看 复制代码
public class NewsCenterFragment extends BaseFragment implements BaseLoadNetDataOperator {

    private static final String TAG = "NewsCenterFragment";
    private NewsCenterBean newsCenterBean;

    @Override
    public void initTitle() {
        setIbMenuDisplayState(true);
        setIbPicTypeDisplayState(false);
        setTitle("新闻中心");
    }

    @Override
    public View createContent() {
        return null;
    }

    @Override
    public void loadNetData() {
        final String url = Constant.NEWSCENTER_URL;
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show(getActivity(), "获取新闻中心数据失败");
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        MyLogger.i(TAG,response);
                        //把response  == json 转换成对应的数据模型
                        processData(response);
                    }
                });
    }

    //把Json格式的字符串转换成对应的模型对象
    public void processData(String json){
        Gson gson = new Gson();
        newsCenterBean = gson.fromJson(json, NewsCenterBean.class);
        //把数据传递给MainActivity
        ((MainActivity)getActivity()).setNewsCenterMenuBeanList(newsCenterBean.data);
    }
}

把新闻中心的json转换成对应的模型对象
格式化json数据

封装javaBean对象:NewsCenterBean
[Java] 纯文本查看 复制代码
/**
 * Created by Apple on 2016/9/26.
 * 新闻中心对应的模型对象
 */
public class NewsCenterBean {
    public List<NewsCenterMenuBean> data;
    public List<String> extend;
    public int retcode;


    //侧滑菜单对应的分类数据
    public class NewsCenterMenuBean{
        public List<NewsCenterNewsTabBean> children;
        public int id;
        public String title;
        public String url;
        public String url1;
        public String dayurl;
        public String excurl;
        public String weekurl;
        public int type;
    }

    //新闻中心新闻tab的模型
    public class NewsCenterNewsTabBean{
        public int id;
        public String title;
        public String url;
        public int type;
    }
}

使用GSON进行转换
[Java] 纯文本查看 复制代码
public class NewsCenterFragment extends BaseFragment implements BaseLoadNetDataOperator {

    private static final String TAG = "NewsCenterFragment";
    private NewsCenterBean newsCenterBean;

    @Override
    public void initTitle() {
        setIbMenuDisplayState(true);
        setIbPicTypeDisplayState(false);
        setTitle("新闻中心");
    }

    @Override
    public View createContent() {
        return null;
    }

    @Override
    public void loadNetData() {
        final String url = Constant.NEWSCENTER_URL;
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show(getActivity(), "获取新闻中心数据失败");
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        MyLogger.i(TAG,response);
                        //把response  == json 转换成对应的数据模型
                        processData(response);
                    }
                });
    }

    //把Json格式的字符串转换成对应的模型对象
    public void processData(String json){
        Gson gson = new Gson();
        newsCenterBean = gson.fromJson(json, NewsCenterBean.class);
        //把数据传递给MainActivity
        ((MainActivity)getActivity()).setNewsCenterMenuBeanList(newsCenterBean.data);
    }
}

把数据传递给MainActivity的侧滑菜单
在MainActivity中声明保存侧滑菜单的数据

将数据传递给MainActivity


1 个回复

倒序浏览
多谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马