Cómo crear una aplicación de Android con un cajón de navegación y pestañas compatibles con 2.3

Ver página de desarrollador de Android:

Cajón de navegación

o esta publicación

Implementé el nuevo cajón de navegación en mi aplicación, pero no puedo entender por qué …

Android – Implementación de Navigation Drawer en Android 2.2 +

Editar:

Android NavigationDrawer con pestañas deslizantes

(ver archivo adjunto)

Tanto NavigationDrawer como NavigationTabs son excelentes para permitir que un usuario navegue por su aplicación. Hay momentos en los que puede necesitar usarlos en conjunto y posible. Sin embargo, no puede usar las pestañas del cajón de navegación ActionBar y de navegación ActionBar juntas. Para usar pestañas, debes implementarlas manualmente en tus fagments.
NavigationDrawer
Google ha documentado cómo implementar el NavigationDrawer aquí. Descargue la aplicación de muestra que se encuentra en la página de documentación porque hay algunos archivos que necesitará:

  • res / drawable / xhdpi / ic_drawer.png
  • res / drawable / xhdpi / drawer_shadow.9.png
  • res / values ​​/ values ​​/ strings.xml

?
res / values ​​/ strings.xml
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12
13
14
15
dieciséis
17
18 años
19
20

DrawerNavigationTabs
Configuración
¡Hola mundo!

Pestañas
WebView

Abrir el cajón de navegación
Cerrar el cajón de navegación
Sección 1
Sección 2
Sección 3

?
res / layout / activity_main.xml
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12
13
14
15
dieciséis
17
18 años
19
20
21
22
23
24
25
26
27
28
29
30

<android.support.v4.widget.DrawerLayout
xmlns: android = “Página en android.com”
android: id = “@ + id / drawer_layout”
android: layout_width = “match_parent”
android: layout_height = “match_parent”>

<! – Como la vista de contenido principal, la vista a continuación consume todo
espacio disponible usando match_parent en ambas dimensiones. ->
<FrameLayout
android: id = “@ + id / content_frame”
android: layout_width = “match_parent”
android: layout_height = “match_parent” />

<! – android: layout_gravity = "start" le dice a DrawerLayout que trate
esto como un cajón deslizante en el lado izquierdo para izquierda a derecha
idiomas y en el lado derecho para idiomas de derecha a izquierda.
El cajón tiene un ancho fijo en dp y extiende la altura total de
El contenedor. Se utiliza un fondo sólido para el contraste.
con la vista de contenido. ->
<ListView
android: id = “@ + id / left_drawer”
android: layout_width = “240dp”
android: layout_height = “match_parent”
android: layout_gravity = “inicio”
android: choiceMode = “singleChoice”
android: divider = “@ android: color / transparent”
android: dividerHeight = “0dp”
android: background = “# 111” />

La mayoría de las veces, un ListView será suficiente para lograr lo que desea mostrar en el cajón.
?
MainActivity.java
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12
13
14
15
dieciséis
17
18 años
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 60
61
62 62
63
64
sesenta y cinco
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129 129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
paquete com.paulusworld.drawernavigationtabs;

importar android.os.Bundle;
importar android.content.res.Configuration;
importar android.support.v4.app.ActionBarDrawerToggle;
importar android.support.v4.app.FragmentActivity;
importar android.support.v4.view.GravityCompat;
importar android.support.v4.widget.DrawerLayout;
importar android.view.MenuItem;
importar android.view.View;
importar android.widget.AdapterView;
importar android.widget.AdapterView.OnItemClickListener;
importar android.widget.ArrayAdapter;
importar android.widget.ListView;

clase pública MainActivity extiende FragmentActivity {

privada estática final String TAG = MainActivity.class.getSimpleName ();

privado DrawerLayout mDrawerLayout;
ListView privado mDrawerList;
privado ActionBarDrawerToggle mDrawerToggle;

CharSequence mDrawerTitle privado;
CharSequence mTitle privado;
Private String [] mDrawerItmes;

@Anular
vacío protegido onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);

mTitle = mDrawerTitle = getTitle ();

mDrawerItmes = getResources (). getStringArray (R.array.drawer_titles);
mDrawerLayout = (DrawerLayout) findViewById (Página en r.id.drawer_layout);
mDrawerList = (ListView) findViewById (Página en r.id.left_drawer);

// establece una sombra personalizada que se superpone al contenido principal cuando se abre el cajón
mDrawerLayout.setDrawerShadow (R.drawable.drawer_shadow, GravityCompat.START);

// Agregar elementos a ListView
mDrawerList.setAdapter (nuevo ArrayAdapter (esto, R.layout.drawer_list_item, mDrawerItmes));
// Establezca OnItemClickListener para que ocurra algo cuando un
// el usuario hace clic en un elemento.
mDrawerList.setOnItemClickListener (nuevo DrawerItemClickListener ());

// Habilita el icono de la aplicación ActionBar para que se comporte como una acción para alternar el NavigationDrawer
getActionBar (). setDisplayHomeAsUpEnabled (verdadero);
getActionBar (). setHomeButtonEnabled (true);

mDrawerToggle = new ActionBarDrawerToggle (
esta,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed (Ver vista) {
getActionBar (). setTitle (mTitle);
invalidateOptionsMenu (); // crea una llamada a onPrepareOptionsMenu
}

public void onDrawerOpened (Ver drawerView) {
getActionBar (). setTitle (mDrawerTitle);
invalidateOptionsMenu (); // crea una llamada a onPrepareOptionsMenu
}
};

mDrawerLayout.setDrawerListener (mDrawerToggle);

// Establece el área de contenido predeterminada en el elemento 0
// cuando la aplicación se abre por primera vez
if (savedInstanceState == null) {
navegar a (0);
}

}

/ *
* Si no tiene ningún menú, aún necesita esta función
* para abrir o cerrar NavigationDrawer cuando el usuario
* haciendo clic en el icono de la aplicación ActionBar.
* /
@Anular
public boolean onOptionsItemSelected (elemento MenuItem) {
if (mDrawerToggle.onOptionsItemSelected (item)) {
volver verdadero;
}

return super.onOptionsItemSelected (item);
}

/ *
* Al usar ActionBarDrawerToggle, debe llamarlo durante onPostCreate ()
* y onConfigurationChanged ()
* /

@Anular
Void protegido en PostCreate (Bundle savedInstanceState) {
super.onPostCreate (savedInstanceState);
mDrawerToggle.syncState ();
}

@Anular
public void onConfigurationChanged (Configuración newConfig) {
super.onConfigurationChanged (newConfig);
mDrawerToggle.onConfigurationChanged (newConfig);
}

clase privada DrawerItemClickListener implementa OnItemClickListener {
@Anular
public void onItemClick (AdapterView parent, View view, int position, long id) {
navegar a (posición);
}
}

private void navigationTo (posición int) {

interruptor (posición) {
caso 0:
getSupportFragmentManager ()
.beginTransaction ()
.replace (Página en r.id.content_frame, TabbedFragment.newInstance (), TabbedFragment.TAG) .commit ();
descanso;
caso 1:
getSupportFragmentManager ()
.beginTransaction ()
.replace (Página en r.id.content_frame,
WebViewFragment.newInstance (),
WebViewFragment.TAG) .commit ();
descanso;
}
mDrawerLayout.closeDrawer (mDrawerList);
}

@Anular
public void setTitle (título de CharSequence) {
mTitle = título;
getActionBar (). setTitle (mTitle);
}

}
?
fragment_webview.xml
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12

<LinearLayout xmlns: android = "Página en android.com"
android: layout_width = “match_parent”
android: layout_height = “match_parent”
android: orientación = “vertical”>

<WebView
android: id = “@ + id / webView”
android: layout_width = “match_parent”
android: layout_height = “match_parent” />

?
WebViewFragment.java
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12
13
14
15
dieciséis
17
18 años
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
paquete com.paulusworld.drawernavigationtabs;

importar android.os.Bundle;
importar android.support.v4.app.Fragment;
importar android.view.LayoutInflater;
importar android.view.View;
importar android.view.ViewGroup;
importar android.webkit.WebView;

WebViewFragment de clase pública extiende Fragment {

Cadena estática pública final TAG = WebViewFragment.class.getSimpleName ();

WebViewFragment público () {
// TODO Trozo de constructor generado automáticamente
}

WebViewFragment estático público newInstance () {
devolver nuevo WebViewFragment ();
}

@Anular
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setRetainInstance (true);
}

@Anular
Public view onCreateView (LayoutInflater inflador, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate (R.layout.fragment_webview, contenedor, falso);
}

@Anular
public void onViewCreated (vista de vista, paquete savedInstanceState) {
super.onViewCreated (view, savedInstanceState);
WebView webView = (WebView) view.findViewById (Página en r.id.webView);
webView.loadUrl (“Inicio | El mundo de Paulus”);
}
}
La forma más fácil de lograr agregar una actividad o fragmento con pestañas en este caso es crear una nueva actividad y seleccionar el tipo de navegación que desea. En este caso, elegí Pestañas desplazables + Deslizar. Una vez que se creó la actividad, tuve que modificar de una FragmentActivity a una Fragment:

  • Elimine la etiqueta para la actividad recién agregada en el archivo AndroidManifest.xml
  • Cambie la función onCreate () a lo que ve aquí.
  • Agregue la función onCreateView ()
  • Se actualizaron los nombres de las clases y diseños.

?
fragment_tabbed.xml
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12
13
14
15
dieciséis
17
18 años
19
20
21
22
23
<android.support.v4.view.ViewPager xmlns: android = "Página en android.com"
xmlns: tools = “Página en android.com”
android: id = “@ + id / pager”
android: layout_width = “match_parent”
android: layout_height = “match_parent”
herramientas: context = “. TabbedFragment”>

<! –
Esta tira de título mostrará el título de la página visible actualmente, así como la página
títulos para páginas adyacentes.
->

<android.support.v4.view.PagerTitleStrip
android: id = “@ + id / pager_title_strip”
android: layout_width = “match_parent”
android: layout_height = “wrap_content”
android: layout_gravity = “top”
android: background = “# 33b5e5”
android: paddingBottom = “4dp”
android: paddingTop = “4dp”
android: textColor = “# fff” />

?
fragment_tabbed_content.xml
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12
13
14
15
dieciséis
<RelativeLayout xmlns: android = "Página en android.com"
xmlns: tools = “Página en android.com”
android: layout_width = “match_parent”
android: layout_height = “match_parent”
android: paddingBottom = “@ dimen / activity_vertical_margin”
android: paddingLeft = “@ dimen / activity_horizontal_margin”
android: paddingRight = “@ dimen / activity_horizontal_margin”
android: paddingTop = “@ dimen / activity_vertical_margin”
herramientas: contexto = “. TabbedActivity $ DummySectionFragment”>

<TextView
android: id = “@ + id / section_label”
android: layout_width = “wrap_content”
android: layout_height = “wrap_content” />

?
TabbedFragment.java
1
2
3
4 4
5 5
6 6
7 7
8
9 9
10
11
12
13
14
15
dieciséis
17
18 años
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 60
61
62 62
63
64
sesenta y cinco
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 91
92
93
94
95
96
97
98
paquete com.paulusworld.drawernavigationtabs;

import java.util.Locale;

importar android.os.Bundle;
importar android.support.v4.app.Fragment;
importar android.support.v4.app.FragmentManager;
importar android.support.v4.app.FragmentPagerAdapter;
importar android.support.v4.view.ViewPager;
importar android.view.LayoutInflater;
importar android.view.View;
importar android.view.ViewGroup;
importar android.widget.TextView;

clase pública TabbedFragment extiende Fragment {

public static final String TAG = TabbedFragment.class.getSimpleName ();
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;

public static TabbedFragment newInstance () {
return new TabbedFragment ();
}

@Anular
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
}

@Anular
Public view onCreateView (LayoutInflater inflador, ViewGroup container, Bundle savedInstanceState) {
Ver v = inflater.inflate (R.layout.fragment_tabbed, contenedor, falso);
mSectionsPagerAdapter = new SectionsPagerAdapter (
getChildFragmentManager ());

mViewPager = (ViewPager) v.findViewById (Página en r.id.pager);
mViewPager.setAdapter (mSectionsPagerAdapter);

volver v;
}

public class SectionsPagerAdapter extiende FragmentPagerAdapter {

public SectionsPagerAdapter (FragmentManager fm) {
super (fm);
}

@Anular
Fragmento público getItem (posición int) {
Fragmento fragmento = nuevo TabbedContentFragment ();
Bundle args = new Bundle ();
args.putInt (TabbedContentFragment.ARG_SECTION_NUMBER, posición + 1);
fragment.setArguments (args);
fragmento de retorno;
}

@Anular
public int getCount () {
retorno 3;
}

@Anular
public CharSequence getPageTitle (int position) {
Locale l = Locale.getDefault ();
interruptor (posición) {
caso 0:
return getString (R.string.title_section1) .toUpperCase (l);
caso 1:
return getString (R.string.title_section2) .toUpperCase (l);
caso 2:
return getString (R.string.title_section3) .toUpperCase (l);
}
volver nulo;
}
}

clase estática pública TabbedContentFragment extiende Fragment {

Cadena final estática pública ARG_SECTION_NUMBER = “section_number”;

public TabbedContentFragment () {
}

@Anular
Vista pública onCreateView (inflador LayoutInflater, contenedor ViewGroup,
Paquete salvadoInstanceState) {
Ver rootView = inflater.inflate (R.layout.fragment_tabbed_content,
contenedor, falso);
TextView dummyTextView = (TextView) rootView
.findViewById (Página en r.id.section_label);
dummyTextView.setText (Integer.toString (getArguments (). getInt (
ARG_SECTION_NUMBER)));
volver rootView;
}
}

}
Archivo adjunto:
NavigationDrawerWithTabs.zip

Mira esta publicación:

Cajón de navegación con pestañas de deslizamiento.