Eu apenas abro a atividade, mas não clico em nenhum item. Mas a função withOnDrawerItemClickListener executa a primeira vez?
Você pode estar configurando a gaveta para abrir a posição 0 na inicialização, o que está acionando o ouvinte. Se precisar de mais ajuda, poste como você adicionou a gaveta.
new DrawerBuilder().withActivity(this).build();
final PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName("Create new order ");
final PrimaryDrawerItem item2 = new PrimaryDrawerItem().withIdentifier(2).withName("Created order");
PrimaryDrawerItem item3 = new PrimaryDrawerItem().withIdentifier(3).withName("Tutorials");
PrimaryDrawerItem item4 = new PrimaryDrawerItem().withIdentifier(4).withName("Your profile");
PrimaryDrawerItem item5 = new PrimaryDrawerItem().withIdentifier(5).withName("About us");
PrimaryDrawerItem item6 = new PrimaryDrawerItem().withIdentifier(6).withName("Version");
PrimaryDrawerItem item7 = new PrimaryDrawerItem().withIdentifier(7).withName("Settings");
PrimaryDrawerItem item8 = new PrimaryDrawerItem().withIdentifier(8).withName("Logout");
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.background_home)
.addProfiles(
new ProfileDrawerItem().withName("Minh").withEmail("Trịnh Văn Minh")//.withIcon(myUri)
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
<strong i="5">@Override</strong>
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
final Drawer result = new DrawerBuilder()
.withActivity(this)
.withAccountHeader(headerResult)
.withToolbar(toolbar)
.addDrawerItems(
item1,
item2,
item3,
item4,
item5,
item6,
item7,
item8
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
<strong i="6">@Override</strong>
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
// do something with the clicked item :D // # On create not click it auto run
if(drawerItem.getIdentifier() ==1)
{
Intent intent = new Intent(getApplicationContext(), HandleMapsActivity.class);
getApplicationContext().startActivity(intent);
}
if(drawerItem.getIdentifier() ==2)
{
Intent intent = new Intent(getApplicationContext(), CreatedOrderActivity.class);
getApplicationContext().startActivity(intent);
}
return false;
}
})
.build();
result.setSelection(1);
result.setSelection(item2);
result.setSelection(1, true);
item1.withBadge("19").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_create_new));
item2.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_created));
item3.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_tutorials));
item4.withBadge("19").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_your_profile));
item5.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_about));
item6.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_version));
item7.withBadge("19").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_settings));
item8.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_logout));
item1.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
<strong i="7">@Override</strong>
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Intent intent = new Intent(getApplicationContext(), HandleMapsActivity.class);
getApplicationContext().startActivity(intent);
return false;
}
});
item2.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
<strong i="8">@Override</strong>
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if(drawerItem.getIdentifier() == 2)
{
Intent intent = new Intent(getApplicationContext(), CreatedOrderActivity.class);
getApplicationContext().startActivity(intent);
}
return true;
}
});
result.openDrawer();
result.closeDrawer();
result.getDrawerLayout();
Essa é a sua implementação real? Você tem algumas instâncias em que construiu a gaveta e não a usou e não precisará abrir e fechar a gaveta imediatamente.
No topo da parte do código formatado, você pode ver result.setSelection(1, true);
, que define a seleção e tem true
que emitirá um evento de clique
Obrigada. Eu entendi, mas como posso definir a seleção para cada item quando um item é clicado? Não é mais seleção de automação. ??
final Drawer result = new DrawerBuilder()
.withActivity(this)
.withAccountHeader(headerResult)
.withToolbar(toolbar)
.addDrawerItems(
item1,
item2,
item3,
item4,
item5,
item6,
item7,
item8
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
<strong i="6">@Override</strong>
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
// do something with the clicked item :D
if(drawerItem.getIdentifier() ==1)
{
Intent intent = new Intent(getApplicationContext(), HandleMapsActivity.class);
getApplicationContext().startActivity(intent);
return true;
}
if(drawerItem.getIdentifier() == 2)
{
Intent intent = new Intent(getApplicationContext(), CreatedOrderActivity.class);
getApplicationContext().startActivity(intent);
return true;
}
return false;
}
})
.build();
item1.withBadge("19").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_create_new));
item2.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_created));
item3.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_tutorials));
item4.withBadge("19").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_your_profile));
item5.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_about));
item6.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_version));
item7.withBadge("19").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_settings));
item8.withBadge("5").withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_green_900)).withIcon(getResources().getDrawable(R.drawable.ic_logout));
@ trinhvanminh2009 retorna false
no ouvinte. true
significa que o evento foi consumido e nenhuma ação adicional é realizada na gaveta em si. Isso é mencionado no JavaDoc desse método.
@mikepenz Obrigado. Eu retorno verdadeiro ou falso sempre tenho um problema. Após startActivity (intent), ele sempre escolhe a seleção (item1). Estou usando esta classe é abstrata e outras classes estendem-se desta classe. Eu não posso usar
result.setSelection (item1) após startActivity. Como posso consertar.
Obrigada.
Eu sei que quando eu inicio a atividade (Intent), então uma nova classe irá atualizar isso. É por isso que sempre seleção (item1). Você pode me dar uma ideia para consertar isso?
@ trinhvanminh2009 Normalmente, a gaveta é anexada à atividade e o conteúdo interno é gerenciado por fragmentos. Talvez você deva olhar para isso em vez de lançar uma nova atividade a cada vez. Se você optar por continuar com a atividade, talvez passe o índice de posição para a próxima atividade e defina a posição da gaveta para esse valor quando ela for carregada. Procure extras de intenção para isso.
Edit: agora vejo que muito do código que você postou corresponde ao do aplicativo de amostra. Lembre-se de que o objetivo desse aplicativo é mostrar muitos estilos de gaveta, por isso ele inicia as atividades. Seu aplicativo provavelmente tem uma finalidade diferente.
Portanto, devo usar fragmento ou intent.putExtra. Eu tenho 2 opções?
@ trinhvanminh2009 Eu sugiro que você examine os fragmentos. Assim, você só terá uma gaveta e não precisará se preocupar com a seleção. Dê uma olhada em como trocar fragmentos , o que você fará quando receber um clique de gaveta
Sim . Eu usei fragmento para mapas do Google e fragmento de diálogo. Mas dessa forma eu nunca tentei antes. Muito obrigado . Vou tentar isso agora.
@AllanWang, obrigado por responder :)
@ trinhvanminh2009 muitas pessoas já o alcançaram usando atividades. É simplesmente mais complicado porque Drawer
não consegue manter o estado adequadamente durante as diferentes atividades e você tem que lidar com o posicionamento, ...
A maioria das pessoas que fez isso criou um BaseActivity
que tinha o código da gaveta e assim por diante.
Lembre-se também de que você pode select
um item de gaveta sem chamar o ouvinte. (Basta ver o JavaDoc)
E você sempre pode lidar com tarefas mais complexas lidando com algumas coisas com o ouvinte.
@mikepenz Obrigado pelo suporte. Estou usando o Drawer no BaseActivity. Mas não está funcionando perfeito como eu penso. Talvez meu código tenha algum problema. Acho que usar Fragment é uma ideia melhor. Usar BaseActivity também é bom, mas como alterar a atividade sem usar a intenção ou como definir a Seleção em onDrawerItemClickListener?
Comentários muito úteis
@ trinhvanminh2009 Normalmente, a gaveta é anexada à atividade e o conteúdo interno é gerenciado por fragmentos. Talvez você deva olhar para isso em vez de lançar uma nova atividade a cada vez. Se você optar por continuar com a atividade, talvez passe o índice de posição para a próxima atividade e defina a posição da gaveta para esse valor quando ela for carregada. Procure extras de intenção para isso.
Edit: agora vejo que muito do código que você postou corresponde ao do aplicativo de amostra. Lembre-se de que o objetivo desse aplicativo é mostrar muitos estilos de gaveta, por isso ele inicia as atividades. Seu aplicativo provavelmente tem uma finalidade diferente.