Uma introdução simples ao aplicativo de material design com animações interessantes e uma API fluente.
Muito inspirado nas introduções de aplicativos do Google.
Um aplicativo de demonstração está disponível no Google Play:
Deslize simples | Slide personalizado | Efeito de esmaecimento | Solicitação de permissão |
---|---|---|---|
SimpleSlide.java | FragmentSlide.java | IntroActivity.java | SimpleSlide.java |
introdução do material está disponível em jitpack.io .
Adicione isto ao seu arquivo build.gradle
raiz ( não ao arquivo build.gradle
do módulo):
allprojects {
repositories {
maven { url ' https://jitpack.io ' }
}
}
Adicione isto ao arquivo build.gradle
do seu módulo:
dependencies {
implementation ' com.heinrichreimersoftware:material-intro:x.y.z '
}
A atividade deve estender IntroActivity
e ter um tema estendendo @style/Theme.Intro
:
public class MainIntroActivity extends IntroActivity {
@ Override
protected void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
// Add slides, edit configuration...
}
}
< manifest ...>
< application ...>
< activity
android : name = " .MainIntroActivity "
android : theme = " @style/Theme.Intro " />
</ application >
</ manifest >
(A menos que mencionado de outra forma, todas as chamadas de método a seguir devem ir para onCreate()
da atividade.)
material-intro possui construtores de estilo fluentes para um slide simples de texto/imagem, como visto nos aplicativos do Google, e para slides com um Fragment
personalizado ou recurso de layout.
Sinta-se à vontade para enviar um problema ou solicitação de pull se achar que algum tipo de slide está faltando.
SimpleSlide
):Slide padrão com título, breve descrição e imagem como as introduções do Google.
addSlide ( new SimpleSlide . Builder ()
. title ( R . string . title_1 )
. description ( R . string . description_1 )
. image ( R . drawable . image_1 )
. background ( R . color . background_1 )
. backgroundDark ( R . color . background_dark_1 )
. scrollable ( false )
. permission ( Manifest . permission . CAMERA )
. build ());
FragmentSlide
): Slide personalizado contendo um Fragment
ou recurso de layout.
addSlide ( new FragmentSlide . Builder ()
. background ( R . color . background_2 )
. backgroundDark ( R . color . background_dark_2 )
. fragment ( R . layout . fragment_2 , R . style . FragmentTheme )
. build ());
(Ao usar FragmentSlide
com um Fragment
, você deve estender SlideFragment
para chamadas de navegação de proxy para a atividade de introdução.)
Slide
):Deslizamento básico. Se você quiser modificar o que é mostrado no seu slide, este é o caminho a seguir.
Controle o comportamento do botão esquerdo ou oculte/mostre-o.
/* Show/hide button */
setButtonBackVisible ( true );
/* Use skip button behavior */
setButtonBackFunction ( BUTTON_BACK_FUNCTION_SKIP );
/* Use back button behavior */
setButtonBackFunction ( BUTTON_BACK_FUNCTION_BACK );
Controle o comportamento do botão direito ou oculte/mostre-o.
/* Show/hide button */
setButtonNextVisible ( true );
/* Use next and finish button behavior */
setButtonNextFunction ( BUTTON_NEXT_FUNCTION_NEXT_FINISH );
/* Use next button behavior */
setButtonNextFunction ( BUTTON_NEXT_FUNCTION_NEXT );
Altere a aparência do botão "call to action":
/* Show/hide button */
setButtonCtaVisible ( getStartedEnabled );
/* Tint button text */
setButtonCtaTintMode ( BUTTON_CTA_TINT_MODE_TEXT );
/* Tint button background */
setButtonCtaTintMode ( BUTTON_CTA_TINT_MODE_BACKGROUND );
/* Set custom CTA label */
setButtonCtaLabel ( R . string . start )
/**/
setButtonCtaClickListener ( new View . OnClickListener () {
});
Exiba a atividade de introdução em tela cheia. Isso oculta a barra de status.
public class MainIntroActivity extends IntroActivity {
@ Override protected void onCreate ( Bundle savedInstanceState ){
setFullscreen ( true );
super . onCreate ( savedInstanceState );
...
}
}
Certifique-se de chamar setFullscreen()
antes de chamar super.onCreate()
Ajuste quanto tempo leva a rolagem de um único slide.
setPageScrollDuration ( 500 );
(A duração da rolagem da página é adaptada dinamicamente ao rolar mais de uma posição para refletir as durações dinâmicas dos documentos do Material Design. A fórmula exata para calcular a duração da rolagem é duration * (distance + sqrt(distance)) / 2
.)
Existem três maneiras de bloquear a navegação de um slide:
SlideFragment
(usando FragmentSlide
), substituindo os métodos canGoForward()
/ canGoBackward()
.SimpleSlide
definindo SimpleSlide.Builder#canGoForward(boolean)
/ SimpleSlide.Builder#canGoBackward(boolean)
. (Se pelo menos uma permissão for definida para SimpleSlide
, a navegação será automaticamente bloqueada até que todas as permissões sejam concedidas.)IntroActivity
, definindo uma NavigationPolicy
: setNavigationPolicy ( new NavigationPolicy () {
@ Override public boolean canGoForward ( int position ) {
return true ;
}
@ Override public boolean canGoBackward ( int position ) {
return false ;
}
});
Navegue pela introdução manualmente usando um dos seguintes métodos, por exemplo, a partir de um retorno de chamada de ouvinte. Cada um deles respeitará as configurações de navegação bloqueadas.
/* Scroll to any position */
goToSlide ( 5 );
/* Scroll to the next slide in the intro */
nextSlide ();
/* Scroll to the previous slide in the intro */
previousSlide ();
/* Scroll to the last slide of the intro */
goToLastSlide ();
/* Scroll to the first slide of the intro */
goToFirstSlide ();
Role automaticamente pela introdução até que o usuário interaja com ela.
/* Start an auto slideshow with 2500ms delay between scrolls and infinite repeats */
autoplay ( 2500 , INFINITE );
/* Start an auto slideshow with default configuration */
autoplay ();
/* Cancel the slideshow */
cancelAutoplay ()
Se alguma das opções acima retornar false
quando um usuário tentar navegar para um slide, um retorno de chamada OnNavigationBlockedListener
será acionado e você poderá usar para exibir uma mensagem. Além disso, você pode adicionar ViewPager.OnPageChangeListener
s antigos para ouvir rolagens de página:
addOnNavigationBlockedListener ( new OnNavigationBlockedListener () {
@ Override public void onNavigationBlocked ( int position , int direction ) { ... }
});
addOnPageChangeListener ( new ViewPager . OnPageChangeListener (){
@ Override public void onPageScrolled ( int position , float positionOffset , int positionOffsetPixels ) { ... }
@ Override public void onPageSelected ( int position ) { ... }
@ Override public void onPageScrollStateChanged ( int state ) { ... }
});
Você pode verificar se o usuário cancelou a introdução (pressionando Voltar) ou finalizou incluindo todos os slides. Basta acessar a atividade usando startActivityForResult(intent, REQUEST_CODE_INTRO);
e ouça o resultado:
@ Override
protected void onActivityResult ( int requestCode , int resultCode , Intent data ) {
super . onActivityResult ( requestCode , resultCode , data );
if ( requestCode == REQUEST_CODE_INTRO ) {
if ( resultCode == RESULT_OK ) {
// Finished the intro
} else {
// Cancelled the intro. You can then e.g. finish this activity too.
finish ();
}
}
}
Você pode facilmente obter um efeito de paralaxe bonito para qualquer slide usando ParallaxFrameLayout.java
, ParallaxLinearLayout.java
ou ParallaxRelativeLayout.java
e definindo layout_parallaxFactor
para seus filhos diretos. Um fator mais alto significa um efeito de paralaxe mais forte, 0
significa nenhum efeito de paralaxe.
< com .heinrichreimersoftware.materialintro.view.parallax.ParallaxLinearLayout
android : layout_width = " match_parent "
android : layout_height = " match_parent "
... >
< TextView
android : layout_width = " match_parent "
android : layout_height = " wrap_content "
app : layout_parallaxFactor = " 0 "
... />
< ImageView
android : layout_width = " match_parent "
android : layout_height = " wrap_content "
app : layout_parallaxFactor = " 1.25 "
... />
</ com .heinrichreimersoftware.materialintro.view.parallax.ParallaxLinearLayout>
Verifique a demonstração "Cantina" para ver um exemplo de layout.
Se quiser mostrar a introdução apenas na primeira inicialização do aplicativo, você pode usar onActivityResult()
para armazenar uma preferência compartilhada quando o usuário terminar a introdução.
Consulte o aplicativo de demonstração para obter um exemplo de implementação da tela inicial:
Veja a seção de lançamentos para changelogs.
material-intro usa os seguintes arquivos de código aberto:
MIT License
Copyright (c) 2017 Jan Heinrich Reimer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.