1 - Navigation Drawer
Android'in resmi sitesindeki tutorial'ı ve örneği inceleyeceğiz aşağıda.
Creating a Navigation Drawer
The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar. ( Navigation drawer, ekranın solunda bir açılır kapanır panel'dir. Navigation drawer çoğunlukla gizlidir ufacık bir kısmı görünü. Bu kısımdan tutup sağa doğru çektiğimizde veya kullanıcı action bar'daki app icon'a tıklayınca navigation drawer'ın tamamı gösterilir. )
Navigation Drawer Design
Before you decide to use a navigation drawer in your app, you should understand the use cases and design principles defined in the Navigation Drawer design guide. ( Navigation drawer kulanmaya karar vermeden önce, bunun user case'lerini ve design principler'larını anlamalısınız, şu linkte anlatılmaktadır : navigation-drawer-use-cases-link )
Create a Drawer Layout
To add a navigation drawer, declare your user interface with a DrawerLayout object as the root view of your layout. Inside the DrawerLayout, add one view that contains the main content for the screen (your primary layout when the drawer is hidden) and another view that contains the contents of the navigation drawer. ( Uygulamanıza bir navigation drawer eklemek için, user interface'inizde root layout olarak DrawerLayout element yazarsınız. DrawerLayout 2 tane bileşene sahiptir, birincisi herhangi bir layout olabilir ikincisi ise navigation drawer listesini içerir. )
For example, the following layout uses a DrawerLayout with two child views: ( Örneğin aşağıdaki örnekteki drawerLayout 2 tane child view'e sahiptir: )
- a FrameLayout to contain the main content (populated by a Fragment at runtime. Container - acts as a container of different screens that will open when you click on drawer items. It can be any layout, not just FrameLayout. ( FrameLayout da olabilir herhangi bir layout da olabilir. Runtime'da içi doldurulacak olan bir FrameLayout. )
- Drawer itself. acts as a remote control. Click on drawer item, and drawer will close and a new screen should open in the container area. a ListView for the navigation drawer. ( Navigation Drawer için bir ListView'dir. Drawer'In kendisidir. Bir ListView'dir. Bu listedeki item'lardan birine tıklayınca drawe kapanır ve yeni bir ekran açılır. )
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
This layout demonstrates some important layout characteristics: ( Yukarıda yazdığımız layout xml dosyası şu özelliklere sahip olmak zorundadır : )
-
The main content view (the FrameLayout above) must be the first child in the DrawerLayout because the XML order implies z-ordering and the drawer must be on top of the content. ( DrawerLayout element'in 1. child view'i, main content view olmak zorundadır yukarıdaki örnekte DrawerLayout element'in sahip olduğu ilk element FrameLayout'dur. )
-
The main content view is set to match the parent view's width and height, because it represents the entire UI when the navigation drawer is hidden. ( main content view, yani yukarıdaki örnekteki FrameLayout'un width ve height'ı match_parent olmak zorundadır. Çünkü navigation drawer gizlendiğinde main content view tüm UI'ı temsil eder. )
-
The drawer view (the ListView) must specify its horizontal gravity with the android:layout_gravity attribute. To support right-to-left (RTL) languages, specify the value with "start" instead of "left" (so the drawer appears on the right when the layout is RTL). ( Drawer view'in (list view'in) horizontal gravity'si android:layout_gravity attribute'ü ile belirtilmek zorundadır. Navigation drawer'ın soldan sağa doğru yazılan diller için soldan, sağdan sola yazılan diller için sağdan belirmesi için drawer view'in android:layout_gravity attribute'ü start olmalıdır. )
-
The drawer view specifies its width in dp units and the height matches the parent view. The drawer width should be no more than 320dp so the user can always see a portion of the main content. ( Drawer view'in genişliği dp biriminden belirtilir 320 dp'den fazla olmamalıdır ki kullanıcı main content'in de bir kısmını görebilsin, yüksekliği ise parent view ile match eder. )
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
The main content view (the FrameLayout above) must be the first child in the DrawerLayout because the XML order implies z-ordering and the drawer must be on top of the content. ( DrawerLayout element'in 1. child view'i, main content view olmak zorundadır yukarıdaki örnekte DrawerLayout element'in sahip olduğu ilk element FrameLayout'dur. )
The main content view is set to match the parent view's width and height, because it represents the entire UI when the navigation drawer is hidden. ( main content view, yani yukarıdaki örnekteki FrameLayout'un width ve height'ı match_parent olmak zorundadır. Çünkü navigation drawer gizlendiğinde main content view tüm UI'ı temsil eder. )
The drawer view (the ListView) must specify its horizontal gravity with the android:layout_gravity attribute. To support right-to-left (RTL) languages, specify the value with "start" instead of "left" (so the drawer appears on the right when the layout is RTL). ( Drawer view'in (list view'in) horizontal gravity'si android:layout_gravity attribute'ü ile belirtilmek zorundadır. Navigation drawer'ın soldan sağa doğru yazılan diller için soldan, sağdan sola yazılan diller için sağdan belirmesi için drawer view'in android:layout_gravity attribute'ü start olmalıdır. )
The drawer view specifies its width in dp units and the height matches the parent view. The drawer width should be no more than 320dp so the user can always see a portion of the main content. ( Drawer view'in genişliği dp biriminden belirtilir 320 dp'den fazla olmamalıdır ki kullanıcı main content'in de bir kısmını görebilsin, yüksekliği ise parent view ile match eder. )
Initialize the Drawer List
In your activity, one of the first things to do is initialize the navigation drawer's list of items. How you do so depends on the content of your app, but a navigation drawer often consists of a ListView, so the list should be populated by an Adapter (such as ArrayAdapter or SimpleCursorAdapter). ( Activity'mizde önce navigation drawer'daki item listesini initialize etmeliyiz. Bunu nasıl yapacağımız uygulamanın içeriğine göre değişir, bu örnekte navigation drawer listview içerdiği için listeyi bir Adapter ile dolduracağız. )
For example, here's how you can initialize the navigation list with a string array: ( Aşağıdaki örnekte layout'daki ListView object'i elde ederiz, bu object'i array adapter ile bağlarız, bu adapter'ün data source'u ise planets_array id'li array'de tanımlanan listeki string'lerdir.
Sonra ise ListView object'in setOnItemClickListener() method'unu çağırarak ListView object'e onItemClickListener register ederiz. NavigationDrawer'daki ListView'deki bir elemana tıklanırsa, setOnItemClickListener() method'unun aldığı DrawerItemClickListener object'in onClick() method'u çağırılır otomatik olarak. Tabi DrawerItemClickListener class'ını ve bu class'da onClick() method'unu tanımlamamız lazım bunun için. )
public class MainActivity extends Activity {
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
...
}
}
This code also calls setOnItemClickListener() to receive click events in the navigation drawer's list. The next section shows how to implement this interface and change the content view when the user selects an item.
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
...
}
}
Handle Navigation Click Events
When the user selects an item in the drawer's list, the system calls onItemClick() on the OnItemClickListener given to setOnItemClickListener(). ( Yukarıdaki örnekte Navigation drawer'daki ListView'in setOnClickListener() method'una verdiğimiz DrawerItemClickListener object'inin class'ını tanımlayacağız şimdi )
In the following example, selecting each item in the list inserts a different Fragment into the main content view (the FrameLayout element identified by the R.id.content_frame ID): ( Aşağıdaki örnekte ListView'deki bir item'a tıklayınca main content view'e(R.id.content_frame id'li FrameLayout element'e) farklı bir fragment insert edilecektir. )
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
Listen for Open and Close Events
To listen for drawer open and close events, call setDrawerListener() on your DrawerLayout and pass it an implementation of DrawerLayout.DrawerListener. This interface provides callbacks for drawer events such as onDrawerOpened() and onDrawerClosed(). ( Navigation Drawer'ın açılması ve kapanması event'ini dinlemek için DrawerLayout object'in setDrawerListener() method'Unu çağırırız, bu method'a argument olarak DrawerLayout.DrawerListener class'ını implement eden bir object veririz. DrawerLayout.DrawerListener class'ında onDrawerOpened() ve onDrawerClosed() callback method'ları tanımlıdır, bu method'ları override ederiz, bu method'lar navigation drawer açıldığında ve kapandığında tetiklenir. )
However, rather than implementing the DrawerLayout.DrawerListener, if your activity includes the action bar, you can instead extend the ActionBarDrawerToggle class. ( Eğer activity'mizde action bar varsa, DrawerLayout.DrawerListener class'ını implement etmektense ActionBarDrawerToggle class'ını extend edebiliriz. ) The ActionBarDrawerToggle implements DrawerLayout.DrawerListener so you can still override those callbacks, but it also facilitates the proper interaction behavior between the action bar icon and the navigation drawer (discussed further in the next section). (ActionBarDrawerToggle class'ı, DrawerLayout.DrawerListener class'ını implement eder. Dolayısıyla DrawerLayout.DrawerListener class'ını implement etmektense ActionBarDrawerToggle class'ını extend edebiliriz.
ActionBarDrawerToggle class'ını extend ettiğimizde, onDrawerOpened() ve onDrawerClosed() callback method'larını override edebiliriz. Ayrıca action bar icon'u ve navigation drawer arasındaki etkileşimden faydalanabiliriz. ActionBarDrawerToggle class'ını kullanarak action bar icon'a tıklayınca navigation drawer'ın açmayı öğreneceğiz sonraki section'da. )
As discussed in the Navigation Drawer design guide, you should modify the contents of the action bar when the drawer is visible, such as to change the title and remove action items that are contextual to the main content. The following code shows how you can do so by overriding DrawerLayout.DrawerListener callback methods with an instance of the ActionBarDrawerToggle class: ( Navigation Drawer açıldığında action bar'ın içeriğini değiştirmelisiniz, mesela action bar'ın title'ını değiştirebilirsiniz ve main content ile alakalı action item'ları silebilirsiniz.
Aşağıdaki kodda buna benzer bir şey yapılmıştır. DrawerLayout.DrawerListener class'ını implement etmektense ActionBarDrawerToggle class'ı extend edilmiştir. onDrawerOpened() ve onDrawerClosed() callback method'ları override edilmiştir. Drawer açıldığında ve kapandığında action bar'ın title'ı değiştirilir ve invalidateOptionsMenu() method'u çağırılır, invalidateOptionsMenu() method'u çağırılınca otomatik olarak onPrepareOptionsMenu() method'u çağırılır bu method'da action_websearch menu item görünür veya görünmez yapılır. )
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
The next section describes the ActionBarDrawerToggle constructor arguments and the other steps required to set it up to handle interaction with the action bar icon. ( Sonraki section'da ActionBarDrawerToggle constructor'ının aldığı argument'leri inceleyeceğiz ve action bar icon ile navigation drawer arasında etkileşim kurmayı öğreneceğiz. )
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
Open and Close with the App Icon
Users can open and close the navigation drawer with a swipe gesture from or towards the left edge of the screen, but if you're using the action bar, you should also allow users to open and close it by touching the app icon. And the app icon should also indicate the presence of the navigation drawer with a special icon. You can implement all this behavior by using the ActionBarDrawerToggle shown in the previous section. ( Navigation drawer'ı soldan sağa ve sağdan parmak çekerek açıp kapatabiliriz. Ama actio bar'ımız varsa kullanıcılar app icon'a tıklayınca da navigation drawer'ın açılmasını sağlamalıyız. Ayrıca app icon'un yanındaki özel bir icon navigation drawer'ın varlığını gösterir. Bunları implement etmek için bir önceki section'da öğrendiğimiz ActionBarDrawerToggle class'ını kullanacağız. )
To make ActionBarDrawerToggle work, create an instance of it with its constructor, which requires the following arguments: (ActionBarDrawerToggle class'ının constructor'ı şu argument'leri alır : )
-
-
-
A drawable resource to use as the drawer indicator. ( Navigation Drawer'ın var olduğunu gösteren icon. )
-
A String resource to describe the "open drawer" action (for accessibility). (Navigation Drawer açıkken kullanılacak string. )
-
A String resource to describe the "close drawer" action (for accessibility). (Navigation Drawer kapalıyken kullanılacak string. )
Then, whether or not you've created a subclass of ActionBarDrawerToggle as your drawer listener, you need to call upon your ActionBarDrawerToggle in a few places throughout your activity lifecycle: (ActionBarDrawerToggle class'ını drawer listener'ınız olarak kullansanız da kullanmasanız da bu class'ı activity'nin farklı yerlerinde kullanmaya ihtiyacınız vardır. Aşağıdaki örnekte activity'nin farklı method'ların bu object kullanılmıştır. )
Activity'nin onOptionsItemSelected() method'unda aşağıdaki kodu yazarak, action bar'da app icon'a tıklayınca navigation drawer'ın açılabilir kapanabilir olmasını sağlarız:
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
...
public void onCreate(Bundle savedInstanceState) {
...
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
...
}
A drawable resource to use as the drawer indicator. ( Navigation Drawer'ın var olduğunu gösteren icon. )
A String resource to describe the "open drawer" action (for accessibility). (Navigation Drawer açıkken kullanılacak string. )
A String resource to describe the "close drawer" action (for accessibility). (Navigation Drawer kapalıyken kullanılacak string. )
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
...
public void onCreate(Bundle savedInstanceState) {
...
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
...
}
Example 1 :
Output :
MainActivity'nin layout'unu inceleyelim. Root element DrawerLayout'dur. DrawerLayout 2 tane child view içerir demiştik daha önce.
DrawerLayout'un içerdiği ilk element olan TextView, NavigationDrawer kapalıyken MainActivity'nin layout'unda gösterilir solda görüldüğü gibi.
DrawerLayout'un içerdiği ikinci element olan ListView, Navigation Drawer'dır, navigation drawer açıldığında bu list view gösterilecektir.
activity_main.xml :
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello Navigation Drawer ! "/>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
MainActivity.java : MainActivity class'ında şu variable'ları declare ederiz :
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
strings.xml'de planets_array isimli bir array tanımladık.
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
MainActivity'de bu array'i elde ederiz :
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
ListView object'i elde ederiz :
mDrawerList = (ListView) findViewById(R.id.left_drawer);
DrawerLayout object'i elde ederiz :
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
Sonra ListView ile array adapter'ü birbirine bağlarız. Array adapter'ün data source'u mPlanetTitles isimli array'dir. Bu listView'deki herbir satırın layout'u drawer_list_item.xml'de tanımlı layout gibi olacaktır:
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles));
Sonra listView'e click listener register ederiz:
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
ListView'deki bir item'a tıklayınca MainActivity class'ında tanımlı inner class olan DrawerItemClickListener class'ındaki onClick() method'u çağırılır:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(MainActivity.this,mPlanetTitles[position] + " is selected !",Toast.LENGTH_LONG).show();
// mDrawerLayout.closeDrawer(mDrawerList);
}
}
DrawerLayout'u swipe ederek kapatabiliriz, bunu yerine tıklayınca kapatılmasını da sağlayabiliriz. Bunun için onItemClick() method'Unda DrawerLayout object'in closeDrawer() method'u çağırılır, closeDrawer() method'Una argument olarak kapatılacak olan drawer'ı yani DrawerList object'i veririz.
MainActivity class'ının tamamı :
public class MainActivity extends AppCompatActivity {
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(MainActivity.this,mPlanetTitles[position] + " is selected !",Toast.LENGTH_LONG).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
drawer_list_item.xml : Drawer olan ListView'deki herbir satırın layout'u aşağıdaki gibidir:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textColor="#fff"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello Navigation Drawer ! "/>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles));
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(MainActivity.this,mPlanetTitles[position] + " is selected !",Toast.LENGTH_LONG).show();
// mDrawerLayout.closeDrawer(mDrawerList);
}
}
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(MainActivity.this,mPlanetTitles[position] + " is selected !",Toast.LENGTH_LONG).show();
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textColor="#fff"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"/>
Bu dersin geri kalan kısmını okumak için bu dersin tamamını içeren pdf'i link'ten indirebilirsiniz :
https://drive.google.com/open?id=13Lv2Ckkz0WUeaKfs-KFOGDlrRBPyh6kd
Bu dersin geri kalan kısmını okumak için bu dersin tamamını içeren pdf'i link'ten indirebilirsiniz :
https://drive.google.com/open?id=13Lv2Ckkz0WUeaKfs-KFOGDlrRBPyh6kd
Hiç yorum yok:
Yorum Gönder