GVKun编程网logo

Ionic2 tabs 导航与 sidemenu 导航结合使用方法(active2导航)

3

以上就是给各位分享Ionic2tabs导航与sidemenu导航结合使用方法,其中也会对active2导航进行解释,同时本文还将给你拓展(5)ionic2--导航、AndroidSlidingTabL

以上就是给各位分享Ionic2 tabs 导航与 sidemenu 导航结合使用方法,其中也会对active2导航进行解释,同时本文还将给你拓展(5)ionic2--导航、Android SlidingTabLayout 的使用 -- 替代 ActionBar 的 Tab 导航、android效果TapBarMenu绘制底部导航栏的使用方式示例、angular – ionic2 – 在sidemenu中添加log等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

Ionic2 tabs 导航与 sidemenu 导航结合使用方法(active2导航)

Ionic2 tabs 导航与 sidemenu 导航结合使用方法(active2导航)

Ionic2 tabs 导航与 sidemenu 导航结合使用方法

我们使用 ionic start -list 查看可用的启动器构建模板,最经常使用的就是 tabs 和 sidemenu,但是如果两种都想用呢(最近经常被人这么问...)?下面就做一个简单的步骤演示一下如何简单的结合两种导航方式.

创建项目

快速创建一个基于 tabs 模板的 Ionic 2 项目并以labs启动:

ionic start tabsidemenu tabs --v2

cd tabsidemenu

ionic serve -l

启动之后,可以看到当前项目是以 tabs 方式进行页面导航的,包含 Home,About,Contact 三个页面:

创建 sidemenu 子页面

使用构建命令快速创建两个页面组件 page1page2:

ionic g page page1

ionic g page page2

然后快速修改一下这两个页面的htmlts文件内容:

src/pages/page1/page1.html

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Page One</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h3>Ionic Menu Starter</h3>

  <p>
    If you get lost,the <a href="http://ionicframework.com/docs/v2">docs</a> will show you the way.
  </p>

  <button ion-button secondary menuToggle>Toggle Menu</button>
</ion-content>

src/pages/page1/page1.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

/*
  Generated class for the Page1 page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-page1',templateUrl: 'page1.html'
})
export class Page1 {

  constructor(public navCtrl: NavController) {}

  ionViewDidLoad() {
    console.log('Hello Page1 Page');
  }

}

src/pages/page1/page2.html

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Page Two</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <button ion-item *ngFor="let item of items" (click)="itemTapped($event,item)">
      <ion-icon [name]="item.icon" item-left></ion-icon>
      {{item.title}}
      <divitem-right>
        {{item.note}}
      </div>
    </button>
  </ion-list>
  <div *ngIf="selectedItem" padding>
    You navigated here from <b>{{selectedItem.title}}</b>
  </div>
</ion-content>

src/pages/page1/page2.ts

import { Component } from '@angular/core';

import { NavController,NavParams } from 'ionic-angular';

/*
 Generated class for the Page2 page.

 See http://ionicframework.com/docs/v2/components/#navigation for more info on
 Ionic pages and navigation.
 */
@Component({
  selector: 'page-page2',templateUrl: 'page2.html'
})
export class Page2 {
  selectedItem: any;
  icons: string[];
  items: Array<{title: string,note: string,icon: string}>;

  constructor(public navCtrl: NavController,public navParams: NavParams) {
    // If we navigated to this page,we will have an item available as a nav param
    this.selectedItem = navParams.get('item');

    // Let's populate this page with some filler content for funzies
    this.icons = ['flask','wifi','beer','football','basketball','paper-plane','american-football','boat','bluetooth','build'];

    this.items = [];
    for (let i = 1; i < 11; i++) {
      this.items.push({
        title: 'Item ' + i,note: 'This is item #' + i,icon: this.icons[Math.floor(Math.random() * this.icons.length)]
      });
    }
  }

  ionViewDidLoad() {
    console.log('Hello Page2 Page');
  }

  itemTapped(event,item) {
    // That's right,we're pushing to ourselves!
    this.navCtrl.push(Page2,{
      item: item
    });
  }
}

并将其引入 app.module.ts :

src/app/app.module.ts

import { NgModule } from '@angular/core';
import { IonicApp,IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import {Page1} from "../pages/page1/page1";
import {Page2} from "../pages/page2/page2";

@NgModule({
  declarations: [
    MyApp,AboutPage,ContactPage,HomePage,TabsPage,Page1,Page2
  ],imports: [
    IonicModule.forRoot(MyApp)
  ],bootstrap: [IonicApp],entryComponents: [
    MyApp,providers: []
})
export class AppModule {}

这样我们的 sidemenu 子页面就简单粗暴的准备好了.

创建 sidemenu 框架页面

项目中的 About 页面是空的,就拿这个页面开刀吧

(5)ionic2--导航

(5)ionic2--导航

在之前的文章中,我们在ListPage类中定义了这样一个方法

itemTapped(event, item) {
    console.log(''You selected:'', item.title);
}

我们做一点改动,实现导航到新页面的功能

itemTapped(event, item) {
    this.nav.push(ItemDetailsPage, {
      item: item
    });
}

 ItemDetailsPage这个页面需要在list.js文件中引入才可以使用哦

import {ItemDetailsPage} from ''../item-details/item-details'';

保存之后, ionic serve 会重新编译你的app,然后载入到浏览器当中.

导航功能实现的原理;

    ionic2中的导航原理类似一个简单的堆栈.如果我们要打开一个新页面,那么这个堆栈就会把这个页面放入栈的顶端,然后显示一个返回按钮.如果我们要返回上一页,我们把这个页面从栈顶剔除.因为我们已经在构造器中创建了this.nav方法,所以在这里可以调用this.nav.push(),传入我们想要到达的页面.我们同时可以传入一个对象,这个对象包含着我们想要传递的数据..使用push()来导航到一个新页面是很简单的,于此同时你也可以自己设置导航的方法,可以google相关文档

Android SlidingTabLayout 的使用 -- 替代 ActionBar 的 Tab 导航

Android SlidingTabLayout 的使用 -- 替代 ActionBar 的 Tab 导航

最近在使用 ActionBar 的时候,如果使用的是最新版 V7 包或者最新的 SDK 平台,就会发现 ActionBar 的导航功能已经不建议使用了。主要的原因是 ActionBar 自带 Tab 导航自定义性差(只能通过 style 修改),而且不再建议使用 ActionBar。SlidingTabLayout 就是 ActionBar 导航的替代品,使用它可以轻松的实现导航功能。

使用 SlidingTabLayout 需要准备 2 个类,分别是 SlidingTabLayout,与 SlidingTabStrip。点击下载 ,放进项目中时只用修改下包名即可。

SlidingTabLayout 主要配合 ViewPager 实现 Tab 导航,且需要在 ActionBarActivity 中使用,具体代码如下:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewPager pager= (ViewPager) findViewById(R.id.pager);
        SlidingTabLayout tab= (SlidingTabLayout) findViewById(R.id.tab);

        MyAdapte adapter= new MyAdapte();
        pager.setAdapter(adapter);
        tab.setViewPager(pager);
    }

    int[] colors={0xFF123456,0xFF654321,0xFF336699};

    class MyAdapte extends PagerAdapter{
        String[] titles={"AA","BB","CC"};

        ArrayList<LinearLayout> layouts=new ArrayList<LinearLayout>();
        MyAdapte() {

            for (int i = 0; i < 3; i++) {
                LinearLayout l=new LinearLayout(MainActivity.this);
                l.setBackgroundColor(colors[i]);
                l.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
                layouts.add(l);
            }

        }

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

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            LinearLayout l=layouts.get(position);
            container.addView(l);
            return l;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(layouts.get(position));
        }
<span style="white-space:pre">    </span>//Tab上显示的文字
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}

布局如下:

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.example.wanggang.slindingtablayouttest001.SlidingTabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/pager" />
</LinearLayout>

运行效果如下:

       

如果要修改 选中效果 的颜色,或者加上选中颜色过度效果,或者 分割线的颜色,可以为 SlidingTabLayout 设置属性

tab.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return colors[position];//每个选项卡所对应的颜色
            }
<span style="white-space:pre">    </span>    //分割线颜色
            @Override
            public int getDividerColor(int position) {
                return 0x00FFFFFF;
            }
        });

效果如下:

 

根据以上的运行效果可以看出,每个 Tab 上面显示的内容都是文本。如果要显示图片,就需要将图片变成  ImageSpan,通过 PagerAdapter  的 getPageTitle () 返回到 SlidingTabLayout。

<span style="white-space:pre">    </span>int[] imageResId = {
                R.drawable.ic_launcher,
                R.drawable.ic_launcher,
                R.drawable.ic_launcher
        };

        @Override
        public CharSequence getPageTitle(int position) {
            Drawable image = getResources().getDrawable(imageResId[position]);
            image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
            SpannableString sb = new SpannableString(" ");
            ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
            sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            return sb;
            //return titles[position];
        }

但是由于 SlidingTabLayout 自带的 TextView 会调用 setAllCaps (true),会取消所有的 ImageSpan 的效果。所以需要自定义 TabView。

res/layout/custom_tab.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="12sp"
    android:gravity="center"
    android:textStyle="bold"
    android:padding="16dp" />

然后在 tab.setViewPager (pager) 之前调用  tab.setCustomTabView (R.layout.custom_tab,0) 设置自定义 TabView

tab.setCustomTabView(R.layout.custom_tab,0);
tab.setViewPager(pager);

运行效果如下:

最后,我们会发现,所有的 TabView 都没有铺满屏幕宽度。如果要每个 TabView 都平分屏幕宽度,只需在自定义的 TextView 上加上权重属性即可。

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:textSize="12sp"
    android:gravity="center"
    android:textStyle="bold"
    android:padding="16dp" />

效果如下:

源码下载

android效果TapBarMenu绘制底部导航栏的使用方式示例

android效果TapBarMenu绘制底部导航栏的使用方式示例

其他的不多说了!我们来看看效果吧

这里写图片描述

     

这里写图片描述

一、实现方式一:直接引入compile方式

Add the dependency to your build.gradle:

compile ‘com.github.michaldrabik:tapbarmenu:1.0.5'

布局设计

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/dark_gray"
 tools:context=".MainActivity">
 <!--中间按钮颜色-->
 <!--app:tbm_backgroundColor="@color/red"-->

 <!--是否初始进入页面就可以看到item图片-->
 <!--app:tbm_showItems="true"-->

 <!--中间按钮大小-->
 <!--app:tbm_buttonSize="30dp"-->

 <!--中间按钮位置-->
 <!--app:tbm_buttonPosition="center"-->

 <!--中间按钮位置左边距-->
 <!--app:tbm_buttonMarginLeft="0dp"-->

 <!--中间按钮位置右边距-->
 <!--app:tbm_buttonMarginRight="0dp"-->

 <!--中间按钮自定义图标打开状态。必须是一个向量可拉的动画。-->
 <!-- app:tbm_iconopened="@drawable/icon"-->

 <!--中间按钮自定义图标关闭状态。必须是一个向量可拉的动画。-->
 <!--app:tbm_iconopened="@drawable/icon"-->

 <!--中间按钮打卡item显示位置-->
 <!--app:tbm_menuAnchor="bottom"-->
 <com.michaldrabik.tapbarmenulib.TapBarMenu
  android:id="@+id/tapBarMenu"
  android:layout_width="match_parent"
  android:layout_height="56dp"
  android:layout_alignParentBottom="true"
  android:layout_marginBottom="24dp"
  app:tbm_backgroundColor="@color/red"
  app:tbm_buttonMarginLeft="0dp"
  app:tbm_buttonMarginRight="0dp"
  app:tbm_buttonPosition="center"
  app:tbm_buttonSize="30dp"
  app:tbm_iconClosed="@drawable/icon"
  app:tbm_iconopened="@drawable/icon"
  app:tbm_menuAnchor="bottom"
  app:tbm_showItems="false">

  <ImageView
   android:id="@+id/item1"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:paddingBottom="10dp"
   android:paddingTop="10dp"
   android:src="@drawable/ic_person"
   tools:visibility="visible" />

  <ImageView
   android:id="@+id/item2"
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_weight="1"
   android:paddingBottom="10dp"
   android:paddingTop="10dp"
   android:src="@drawable/ic_location" />

  <Space
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_weight="1" />

  <ImageView
   android:id="@+id/item3"
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_weight="1"
   android:paddingBottom="10dp"
   android:paddingTop="10dp"
   android:src="@drawable/ic_thumb_up" />

  <ImageView
   android:id="@+id/item4"
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_weight="1"
   android:paddingBottom="10dp"
   android:paddingTop="10dp"
   android:src="@drawable/ic_thumb_down" />

 </com.michaldrabik.tapbarmenulib.TapBarMenu>

 

</RelativeLayout>

这里写图片描述

在Activity中的代码

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.michaldrabik.tapbarmenulib.TapBarMenu;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

 @Bind(R.id.tapBarMenu)
 TapBarMenu tapBarMenu;

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

 private boolean isClick = true;

 @OnClick(R.id.tapBarMenu)
 public void onMenuButtonClick() {
//  if (isClick) {
//   tapBarMenu.toggle();
//   isClick = false;
//  }
  tapBarMenu.toggle();
 }

 @OnClick({R.id.item1,R.id.item2,R.id.item3,R.id.item4})
 public void onMenuItemClick(View view) {
// tapBarMenu.close();
  switch (view.getId()) {
   case R.id.item1:
    Toast.makeText(this,"item1",Toast.LENGTH_LONG).show();
    break;
   case R.id.item2:
    Toast.makeText(this,"item2",Toast.LENGTH_LONG).show();
    break;
   case R.id.item3:
    Toast.makeText(this,"item3",Toast.LENGTH_LONG).show();
    break;
   case R.id.item4:
    Toast.makeText(this,"item4",Toast.LENGTH_LONG).show();
    break;
  }
 }
}

到这里效果就基本实现了

二、实现方式二:引入Module方式

module中记得引入

compile ‘com.wnafee:vector-compat:1.0.5'

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;

import com.wnafee.vector.compat.ResourcesCompat;

/**
 * TapBar Menu Layout.
 *
 * @author Michal Drabik (michal.drabik0@gmail.com) on 2015-11-13.
 */
public class TapBarMenu extends LinearLayout {

 public static final int BUTTON_POSITION_LEFT = 0;
 public static final int BUTTON_POSITION_CENTER = 1;
 public static final int BUTTON_POSITION_RIGHT = 2;
 public static final int MENU_ANCHOR_BottOM = 3;
 public static final int MENU_ANCHOR_TOP = 4;
 private static final DecelerateInterpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator(2.5f);

 private enum State {
  OPENED,CLOSED
 }

 private static final int LEFT = 0;
 private static final int RIGHT = 1;
 private static final int TOP = 2;
 private static final int BottOM = 3;
 private static final int RADIUS = 4;

 private AnimatorSet animatorSet = new AnimatorSet();
 private ValueAnimator[] animator = new ValueAnimator[5];
 private float[] button = new float[5];

 private Path path = new Path();
 private State state = State.CLOSED;
 private Paint paint;
 private int animationDuration;
 private float width;
 private float height;
 private float buttonLeftinitial;
 private float buttonRightinitial;
 private float yPosition;
 private Drawable iconopenedDrawable;
 private Drawable iconClosedDrawable;
 private OnClickListener onClickListener;

 //Custom XML Attributes
 private int backgroundColor;
 private int buttonSize;
 private int buttonPosition;
 private int buttonMarginRight;
 private int buttonMarginLeft;
 private int menuAnchor;
 private boolean showMenuItems;

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

 public TapBarMenu(Context context,AttributeSet attrs,int defStyleAttr) {
  super(context,attrs,defStyleAttr);
  init(attrs);
 }

 private void init(AttributeSet attrs) {
  setwillNotDraw(false);
  setupAttributes(attrs);
  setGravity(Gravity.CENTER);
  setupAnimators();
  setupPaint();
 }

 private void setupAttributes(AttributeSet attrs) {
  TypedArray typedArray = getContext().obtainStyledAttributes(attrs,R.styleable.TapBarMenu,0);

  if (typedArray.hasValue(R.styleable.TapBarMenu_tbm_iconopened)) {
   iconopenedDrawable = typedArray.getDrawable(R.styleable.TapBarMenu_tbm_iconopened);
  } else {
   iconopenedDrawable = ResourcesCompat.getDrawable(getContext(),R.drawable.icon_animated);
  }

  if (typedArray.hasValue(R.styleable.TapBarMenu_tbm_iconClosed)) {
   iconClosedDrawable = typedArray.getDrawable(R.styleable.TapBarMenu_tbm_iconClosed);
  } else {
   iconClosedDrawable = ResourcesCompat.getDrawable(getContext(),R.drawable.icon_close_animated);
  }

  backgroundColor = typedArray.getColor(R.styleable.TapBarMenu_tbm_backgroundColor,ContextCompat.getColor(getContext(),R.color.red));
  buttonSize =
    typedArray.getDimensionPixelSize(R.styleable.TapBarMenu_tbm_buttonSize,getResources().getDimensionPixelSize(R.dimen.defaultButtonSize));
  buttonMarginRight = typedArray.getDimensionPixelSize(R.styleable.TapBarMenu_tbm_buttonMarginRight,0);
  buttonMarginLeft = typedArray.getDimensionPixelSize(R.styleable.TapBarMenu_tbm_buttonMarginLeft,0);
  buttonPosition = typedArray.getInt(R.styleable.TapBarMenu_tbm_buttonPosition,BUTTON_POSITION_CENTER);
  menuAnchor = typedArray.getInt(R.styleable.TapBarMenu_tbm_menuAnchor,MENU_ANCHOR_BottOM);
  showMenuItems = typedArray.getBoolean(R.styleable.TapBarMenu_tbm_showItems,false);
  typedArray.recycle();
 }

 private void setupAnimators() {
  for (int i = 0; i < 5; i++) {
   animator[i] = new ValueAnimator();
  }

  animator[LEFT].addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    button[LEFT] = (float) valueAnimator.getAnimatedValue();
   }
  });
  animator[RIGHT].addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    button[RIGHT] = (float) valueAnimator.getAnimatedValue();
   }
  });
  animator[TOP].addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    button[TOP] = (float) valueAnimator.getAnimatedValue();
   }
  });
  animator[BottOM].addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    button[BottOM] = (float) valueAnimator.getAnimatedValue();
   }
  });
  animator[RADIUS].addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
   @Override
   public void onAnimationUpdate(ValueAnimator valueAnimator) {
    button[RADIUS] = (float) valueAnimator.getAnimatedValue();
    invalidate();
   }
  });
  animationDuration = getResources().getInteger(R.integer.animationDuration);
  animatorSet.setDuration(animationDuration);
  animatorSet.setInterpolator(DECELERATE_INTERPOLATOR);
  animatorSet.playTogether(animator);
 }

 private void setupMenuItems() {
  for (int i = 0; i < getChildCount(); i++) {
   getChildAt(i).setVisibility(showMenuItems ? VISIBLE : GONE);
  }
 }

 private void setupPaint() {
  paint = new Paint();
  paint.setColor(backgroundColor);
  paint.setAntiAlias(true);
 }

 @Override
 protected void onAttachedToWindow() {
  super.onAttachedToWindow();
  setupMenuItems();
 }

 /**
  * Opens the menu if it's closed or close it if it's opened.
  */
 public void toggle() {
  if (state == State.OPENED)
   close();
  else
   open();
 }

 /**
  * Open the menu.
  */
 public void open() {
  state = State.OPENED;
  showIcons(true);

  animator[LEFT].setFloatValues(button[LEFT],0);
  animator[RIGHT].setFloatValues(button[RIGHT],width);
  animator[RADIUS].setFloatValues(button[RADIUS],0);
  animator[TOP].setFloatValues(button[TOP],0);
  animator[BottOM].setFloatValues(button[BottOM],height);

  animatorSet.cancel();
  animatorSet.start();
  if (iconopenedDrawable instanceof Animatable) {
   ((Animatable) iconopenedDrawable).start();
  }
  ViewGroup parentView = (ViewGroup) TapBarMenu.this.getParent();
  this.animate()
    .y(menuAnchor == MENU_ANCHOR_BottOM ? parentView.getBottom() - height : 0)
    .setDuration(animationDuration)
    .setInterpolator(DECELERATE_INTERPOLATOR)
    .start();
 }

 /**
  * Close the menu.
  */
 public void close() {
  updateDimensions(width,height);
  state = State.CLOSED;
  showIcons(false);

  animator[LEFT].setFloatValues(0,button[LEFT]);
  animator[RIGHT].setFloatValues(width,button[RIGHT]);
  animator[RADIUS].setFloatValues(0,button[RADIUS]);
  animator[TOP].setFloatValues(0,button[TOP]);
  animator[BottOM].setFloatValues(height,button[BottOM]);

  animatorSet.cancel();
  animatorSet.start();
  if (iconClosedDrawable instanceof Animatable) {
   ((Animatable) iconClosedDrawable).start();
  }
  this.animate()
    .y(yPosition)
    .setDuration(animationDuration)
    .setInterpolator(DECELERATE_INTERPOLATOR)
    .start();
 }

 /**
  * @return True if menu is opened. False otherwise.
  */
 public boolean isOpened() {
  return state == State.OPENED;
 }

 /**
  * Sets TapBarMenu's background color from given resource.
  *
  * @param colorResId Color resource id. For example: R.color.holo_blue_light
  */
 public void setMenuBackgroundColor(int colorResId) {
  backgroundColor = ContextCompat.getColor(getContext(),colorResId);
  paint.setColor(backgroundColor);
  invalidate();
 }

 /**
  * Set position of 'Open Menu' button.
  *
  * @param position One of: {@link #BUTTON_POSITION_CENTER},{@link #BUTTON_POSITION_LEFT},{@link #BUTTON_POSITION_RIGHT}.
  */
 public void setButtonPosition(int position) {
  buttonPosition = position;
  invalidate();
 }

 /**
  * Sets diameter of 'Open Menu' button.
  *
  * @param size Diameter in pixels.
  */
 public void setButtonSize(int size) {
  buttonSize = size;
  invalidate();
 }

 /**
  * Sets left margin for 'Open Menu' button.
  *
  * @param margin Left margin in pixels
  */
 public void setButtonMarginLeft(int margin) {
  buttonMarginLeft = margin;
 }

 /**
  * Sets right margin for 'Open Menu' button.
  *
  * @param margin Right margin in pixels
  */
 public void setButtonMarginRight(int margin) {
  buttonMarginRight = margin;
 }

 /**
  * Set anchor point of the menu. Can be either bottom or top.
  *
  * @param anchor One of: {@link #MENU_ANCHOR_BottOM},{@link #MENU_ANCHOR_TOP}.
  */
 public void setAnchor(int anchor) {
  menuAnchor = anchor;
 }

 /**
  * Sets the passed drawable as the drawable to be used in the open state.
  *
  * @param openDrawable The open state drawable
  */
 public void setIconopenDrawable(Drawable openDrawable) {
  this.iconopenedDrawable = openDrawable;
  invalidate();
 }

 /**
  * Sets the passed drawable as the drawable to be used in the closed state.
  *
  * @param closeDrawable The closed state drawable
  */
 public void setIconCloseDrawable(Drawable closeDrawable) {
  this.iconClosedDrawable = closeDrawable;
  invalidate();
 }

 /**
  * Sets the passed drawable as the drawable to be used in the open state.
  *
  * @param openDrawable The open state drawable
  */
 public void setIconopenedDrawable(Drawable openDrawable) {
  this.iconopenedDrawable = openDrawable;
  invalidate();
 }

 /**
  * Sets the passed drawable as the drawable to be used in the closed state.
  *
  * @param closeDrawable The closed state drawable
  */
 public void setIconClosedDrawable(Drawable closeDrawable) {
  this.iconClosedDrawable = closeDrawable;
  invalidate();
 }

 @Override
 public void setonClickListener(OnClickListener listener) {
  onClickListener = listener;
 }

 @Override
 protected void onSizeChanged(int w,int h,int oldw,int oldh) {
  super.onSizeChanged(w,h,oldw,oldh);
  updateDimensions(w,h);
  yPosition = getY();
 }

 @Override
 protected void onDraw(Canvas canvas) {
  canvas.drawPath(createRoundedRectPath(button[LEFT],button[TOP],button[RIGHT],button[BottOM],button[RADIUS],false),paint);
  if (state == State.CLOSED) {
   iconClosedDrawable.draw(canvas);
  } else {
   iconopenedDrawable.draw(canvas);
  }
 }

 private void updateDimensions(float w,float h) {
  int ratio;
  width = w;
  height = h;

  button[RADIUS] = buttonSize;
  setButtonPosition(width);
  if (iconClosedDrawable instanceof Animatable) {
   ratio = 3;
  } else {
   ratio = 5;
  }
  float iconLeft = button[LEFT] + buttonSize / ratio;
  float iconTop = (height - buttonSize) / 2 + buttonSize / ratio;

  float iconRight = button[RIGHT] - buttonSize / ratio;
  float iconBottom = (height + buttonSize) / 2 - buttonSize / ratio;
  iconopenedDrawable.setBounds((int) iconLeft,(int) iconTop,(int) iconRight,(int) iconBottom);
  iconClosedDrawable.setBounds((int) iconLeft,(int) iconBottom);
 }

 private void setButtonPosition(float width) {
  if (buttonPosition == BUTTON_POSITION_CENTER) {
   button[LEFT] = ((width / 2) - (buttonSize / 2));
  } else if (buttonPosition == BUTTON_POSITION_LEFT) {
   button[LEFT] = 0;
  } else {
   button[LEFT] = width - buttonSize;
  }
  int padding = buttonMarginLeft - buttonMarginRight;
  button[LEFT] += padding;
  button[RIGHT] = button[LEFT] + buttonSize;
  button[TOP] = (height - buttonSize) / 2;
  button[BottOM] = (height + buttonSize) / 2;
  buttonLeftinitial = button[LEFT];
  buttonRightinitial = button[RIGHT];
 }

 private void showIcons(final boolean show) {
  for (int i = 0; i < getChildCount(); i++) {
   final View view = getChildAt(i);
   int translation = menuAnchor == MENU_ANCHOR_BottOM ? view.getHeight() : -view.getHeight();
   if (show){
    view.setTranslationY(Float.valueOf(translation));
   }else {
    view.setTranslationY(0f);
   }
//   view.setTranslationY(show ? translation : 0f);
   view.setScaleX(show ? 0f : 1f);
   view.setScaleY(show ? 0f : 1f);
   view.setVisibility(VISIBLE);
   view.setAlpha(show ? 0f : 1f);
   view.animate()
     .scaleX(show ? 1f : 0f)
     .scaleY(show ? 1f : 0f)
     .translationY(0f)
     .alpha(show ? 1f : 0f)
     .setInterpolator(DECELERATE_INTERPOLATOR)
     .setDuration(show ? animationDuration / 2 : animationDuration / 3)
     .setStartDelay(show ? animationDuration / 3 : 0)
     .setListener(new AnimatorListenerAdapter() {
      @Override
      public void onAnimationEnd(Animator animation) {
       super.onAnimationEnd(animation);
       view.setVisibility(show ? VISIBLE : GONE);
      }
     })
     .start();
  }
 }

 private Path createRoundedRectPath(float left,float top,float right,float bottom,float rx,float ry,boolean conformToOriginalPost) {
  path.reset();
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   return createRoundedRectPathApi21(path,left,top,right,bottom,rx,ry,conformToOriginalPost);
  } else {
   return createRoundedRectPathPreApi21(path,conformToOriginalPost);
  }
 }

 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 private Path createRoundedRectPathApi21(Path path,float left,boolean
   conformToOriginalPost) {
  if (rx < 0) rx = 0;
  if (ry < 0) ry = 0;
  float width = right - left;
  float height = bottom - top;
  if (rx > width / 2) rx = width / 2;
  if (ry > height / 2) ry = height / 2;
  float widthMinusCorners = (width - (2 * rx));
  float heightMinusCorners = (height - (2 * ry));
  path.moveto(right,top + ry);
  path.arcTo(right - 2 * rx,top + 2 * ry,-90,false);
  path.rLineto(-widthMinusCorners,0);
  path.arcTo(left,left + 2 * rx,270,false);
  path.rLineto(0,heightMinusCorners);
  if (conformToOriginalPost) {
   path.rLineto(0,ry);
   path.rLineto(width,0);
   path.rLineto(0,-ry);
  } else {
   path.arcTo(left,bottom - 2 * ry,180,false);
   path.rLineto(widthMinusCorners,0);
   path.arcTo(right - 2 * rx,90,false);
  }
  path.rLineto(0,-heightMinusCorners);
  path.close();
  return path;
 }

 private Path createRoundedRectPathPreApi21(Path path,top + ry);
  path.rQuadTo(0,-ry,-rx,-ry);
  path.rLineto(-widthMinusCorners,0);
  path.rQuadTo(-rx,ry);
  path.rLineto(0,-ry);
  } else {
   path.rQuadTo(0,ry);
   path.rLineto(widthMinusCorners,0);
   path.rQuadTo(rx,-ry);
  }
  path.rLineto(0,-heightMinusCorners);
  path.close();
  return path;
 }

 @Override
 public boolean onInterceptTouchEvent(MotionEvent event) {
  return (event.getX() > buttonLeftinitial && event.getX() < buttonRightinitial);
 }

 @Override
 public boolean onTouchEvent(@NonNull MotionEvent event) {
  if ((event.getX() > buttonLeftinitial && event.getX() < buttonRightinitial) && (event.getAction() == MotionEvent.ACTION_UP)) {
   if (onClickListener != null) {
    onClickListener.onClick(this);
   }
  }
  return true;
 }

 @Override
 protected void onDetachedFromWindow() {
  onDestroy();
  super.onDetachedFromWindow();
 }

 private void onDestroy() {
  iconopenedDrawable = null;
  iconClosedDrawable = null;
  for (int i = 0; i < 5; i++) {
   animator[i] = null;
  }
  animator = null;
  button = null;
  onClickListener = null;
 }
}

布局和代码与上面一致,module请下载:

链接:http://pan.baidu.com/s/1o8jlnpo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

angular – ionic2 – 在sidemenu中添加log

angular – ionic2 – 在sidemenu中添加log

我正在使用sidemenu模板来开始我的应用程序.我想在sidemenu中添加一个按钮,以便用户启动注销警报模式以确认注销.这是我的代码:

app.component.ts:

import { Component,ViewChild } from '@angular/core';
import { Nav,Platform } from 'ionic-angular';
import { StatusBar,Splashscreen } from 'ionic-native';

import { Home } from '../pages/home/home';
import { Profile } from '../pages/profile/profile';
import { logout } from '../pages/logout/logout';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = Home;

  pages: Array<{title: string,component: any}>;

  constructor(public platform: Platform,public logout:logout) {
    this.initializeApp();

    // used for an example of ngFor and navigation
    this.pages = [
      { title: 'Home',component: Home },{ title: 'Profile',component: Profile }
    ];

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay,so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  logoutApp(){ ///<-- call from static button
    this.logout.presentConfirm(); ///<-- call 
  }

}

app.html:

<ion-menu [content]="content">
  <ion-content>
    <ion-list>
      <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
        {{p.title}}
      </button>
      <button ion-item (click)="logoutApp()">
      <!--Add this static button for logout-->
        Log Out
      </button>
    </ion-list>

  </ion-content>

</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

app.module.ts:

import { NgModule } from '@angular/core';
import { IonicApp,IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';

import { Home } from '../pages/home/home';
import { Profile } from '../pages/profile/profile';
import { logout } from '../pages/logout/logout';

@NgModule({
  declarations: [
    MyApp,Home,Profile,logout
  ],imports: [
    IonicModule.forRoot(MyApp)
  ],bootstrap: [IonicApp],entryComponents: [
    MyApp,providers: []
})
export class AppModule {}

logout.ts:

import { Component } from '@angular/core';
import { AlertController } from 'ionic-angular';

@Component({
  template: ``
})
export class logout {
  constructor(
    public alertCtrl: AlertController
  ) { }

presentConfirm() {
  let alert = this.alertCtrl.create({
    title: 'Confirm Log Out',message: 'Are you sure you want to log out?',buttons: [
      {
        text: 'Cancel',role: 'cancel',handler: () => {
          console.log('Cancel clicked');
        }
      },{
        text: 'Log Out',handler: () => {
          console.log('Logged out');
        }
      }
    ]
  });
  alert.present();
}

}

根据我的知识,这应该足够了.但是我收到了一个错误:

45EXCEPTION: Error in ./MyApp class MyApp_Host – inline template:0:0
caused by: No provider for logout!

但为什么我们需要提供者呢?有什么我错过了吗?

解决方法

注销不是提供者(它是一个组件),但您正在尝试将其注入MyApp.从它的外观来看,看起来你的意图并不是真正使logout成为一个组件.在这种情况下,您应该用@Injectable()替换@Component()

import { Injectable } from '@angular/core';

@Injectable()
export class logout {
}

然后将其从@ NgModule.declarations和@ NgModule.entryComponent中删除,并将其添加到@ NgModule.providers

@NgModule({
  declarations: [
    // logout
  ],entryComponents: [
    // logout
  ],providers: [
    logout
  ]
})
class AppModule {}

如果logout应该是一个组件,并且您希望能够在MyApp中从它访问一个方法,那么您应该做的是创建一个可以注入logout和MyApp的服务,这可以使用服务功能提出警报.

我们今天的关于Ionic2 tabs 导航与 sidemenu 导航结合使用方法active2导航的分享就到这里,谢谢您的阅读,如果想了解更多关于(5)ionic2--导航、Android SlidingTabLayout 的使用 -- 替代 ActionBar 的 Tab 导航、android效果TapBarMenu绘制底部导航栏的使用方式示例、angular – ionic2 – 在sidemenu中添加log的相关信息,可以在本站进行搜索。

本文标签: