Home Java javaTutorial Android DrawerLayout layout class with side sliding function (1)

Android DrawerLayout layout class with side sliding function (1)

Jan 07, 2017 pm 02:32 PM

DrawerLayout, as the name suggests, is a management layout. The usage can be similar to other layout classes.
DrawerLayout has a sliding function. As long as the layout is written according to the prescribed layout method of drawerLayout, you can have a side-sliding effect.
Directly use DrawerLayout as the root layout, and then inside it

The first View is the content area

The second View is the left menu

The three Views are the right side sliding menu

The third one is currently optional.
The packages used are as follows:
import android.support.v4.widget.DrawerLayout;

Sometimes errors will be reported when using these packages. At this time, make sure that android.support.v4 is the latest version.
You can update the support package, the file is stored in sdk/extres/support.
Then you can use eclipse>project right click>Android Tools>Add Support library...
Or you can copy the file directly to the libs folder in Project.

<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">
 <FrameLayout
  android:id="@+id/content_frame"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />
 <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>
Copy after login

Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right.
(Or start/end on platform versions that support layout direction.)
That is to say
android:layout_gravity="start" is equivalent to the MENU on the left. Swipe to the right to display the menu, LEFT/START (RIGHT/END)
Then from It can be seen from the layout file:
FrameLayout is the content area, and ListView is the left menu.
We need to make a Fragment to load the content:

public class PageFragment extends Fragment {
  public final static String ITEM_POSITION_NUMBER = "item_position_num";
  public PageFragment(){}
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
   View convertView = inflater.inflate(R.layout.page_fragment_layout, null);
   TextView tv = (TextView) convertView.findViewById(R.id.textView);
   int num = getArguments().getInt(ITEM_POSITION_NUMBER);
   //从res/array中获取list数据
   String[] dynastyList = getResources().getStringArray(R.array.list_item);
   tv.setText(dynastyList[num]);
   return convertView;
  }
 }
Copy after login

It can be seen from the code that when we select SelectItem in the left menu, the corresponding value will be displayed in the content area.
The page_fragment_layout.xml in the code only adds a TextView to the FrameLayout, so the code will not be posted.
Next we need to fill the listView with data.

private ListView menuList;
private String[] mMenuTitles;
private String[] historyTitles;
private String[] musicTitles;
private String[] movieTitles;
private String[] listTitles;
     // 历史栏
  historyTitles = getResources().getStringArray(R.array.history);
  // 音乐栏
  musicTitles = getResources().getStringArray(R.array.music);
  // 电影栏
  movieTitles = getResources().getStringArray(R.array.movie);
  // 标题数组
  mMenuTitles = getResources().getStringArray(R.array.title);
  // 每一項的標題
  listTitles = getResources().getStringArray(R.array.list_item);
 
  drawLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
  menuList = (ListView) findViewById(R.id.left_menu);
 
  // 设置菜单阴影效果
  // drawLayout.setDrawerShadow(R.drawable.drawer_shadow,
  // GravityCompat.START);
  List<Item> list = new ArrayList<Item>();
  // 菜单加入历史标题和历史项
  HeaderItem historyHeader = new HeaderItem(mMenuTitles[0]);
  list.add(historyHeader);
  for (int i = 0; i < historyTitles.length; i++) {
   EventItem historyitem = new EventItem(historyTitles[i]);
   list.add(historyitem);
  }
 
  // 菜单加入音乐标题和音乐项
  HeaderItem musicHeader = new HeaderItem(mMenuTitles[1]);
  list.add(musicHeader);
  for (int i = 0; i < musicTitles.length; i++) {
   EventItem musicItem = new EventItem(musicTitles[i]);
   list.add(musicItem);
  }
 
  // 菜单加入电影标题和电影项
  HeaderItem movieHeader = new HeaderItem(mMenuTitles[2]);
  list.add(movieHeader);
  for (int i = 0; i < movieTitles.length; i++) {
   EventItem movieItem = new EventItem(movieTitles[i]);
   list.add(movieItem);
  }
 
  MyListAdapter adapter = new MyListAdapter(this, list);
  menuList.setAdapter(adapter);
Copy after login

This data filling is a bit troublesome. Customize ListAdapter and then adapt it.
The data is in res/values/arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string-array name="history">
  <item >三国</item>
  <item >楚汉</item>
  <item >春秋</item>
  <item >战国</item>
 </string-array>
  <string-array name="music">
  <item >爵士</item>
  <item >古典</item>
  <item >现代</item>
  <item >民谣</item>
 </string-array>
  <string-array name="movie">
  <item >悬疑</item>
  <item >爱情</item>
  <item >历史</item>
  <item >恐怖</item>
 </string-array>
 <string-array name="title">
  <item >历史</item>
  <item >音樂</item>
  <item >电影</item>
 </string-array>
 <string-array name="list_item">
  <item >歷史</item>
  <item >三国</item>
  <item >楚汉</item>
  <item >春秋</item>
  <item >战国</item>
  <item >音樂</item>
  <item >爵士</item>
  <item >古典</item>
  <item >现代</item>
  <item >民谣</item>
  <item >電影</item>
  <item >悬疑</item>
  <item >爱情</item>
  <item >历史</item>
  <item >恐怖</item>
 </string-array>
</resources>
Copy after login

Then there is the monitoring of listView:

 private void initListener() {
 // 菜单单击事件监听器
 menuList.setOnItemClickListener(new DrawerItemClickListener());
}
 
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
  ListView.OnItemClickListener {
 @Override
 public void onItemClick(AdapterView<?> parent, View view, int position,
   long id) {
  Log.i("Light", "position:" + position);
  selectItem(position);
 }
}
 
private void selectItem(int position) {
 // update the main content by replacing fragments
 PageFragment fragment = new PageFragment();
 // 将当前选择的项传递到Fragment
 Bundle args = new Bundle();
 args.putInt(PageFragment.ITEM_POSITION_NUMBER, position);
 fragment.setArguments(args);
 
 FragmentTransaction ft = MainActivity.this.getSupportFragmentManager()
   .beginTransaction();
 ft.replace(R.id.content_frame, fragment).commit();
 
 drawLayout.closeDrawer(menuList);
 // update selected item and title, then close the drawer
 menuList.setItemChecked(position, true);
 // 注意这里改变的是ActionBar的标题
 getActionBar().setTitle(listTitles[position]);
}
Copy after login

What we care about is what happens when an Item is clicked, that is, the code:

private void selectItem(int position) {
  // update the main content by replacing fragments
  PageFragment fragment = new PageFragment();
  // 将当前选择的项传递到Fragment
  Bundle args = new Bundle();
  args.putInt(PageFragment.ITEM_POSITION_NUMBER, position);
  fragment.setArguments(args);
 
  FragmentTransaction ft = MainActivity.this.getSupportFragmentManager()
    .beginTransaction();
  ft.replace(R.id.content_frame, fragment).commit();
 
  drawLayout.closeDrawer(menuList);
  // update selected item and title, then close the drawer
  menuList.setItemChecked(position, true);
  // 注意这里改变的是ActionBar的标题
  getActionBar().setTitle(listTitles[position]);
 }
Copy after login

It can be seen from the code
1. First, we first obtain the content area through new PageFragment();.
2. Package the data through Bundle and inject it into fragment.setArguments(args); so that the fragment can obtain this data.
In the fragment class, you can get the passed value through getArguments().getInt(ITEM_POSITION_NUMBER);.
3. Then replace the content with the previously defined PageFragment through ft.replace(R.id.content_frame, fragment).commit();
4. Close the menu through drawLayout.closeDrawer(menuList); throughout the code We only use the function DrawLayout
5. At the same time, change the title of the ActionBar to the value corresponding to selectedItem.
*At this time, someone will ask us why there is no binding operation between ListView and DrawerLayout. We have also said before that the second start in DrawerLayout is the menu View, which has been bound internally.
Only these contents can realize the left and right sliding menu effect.

Android DrawerLayout 侧滑 布局类

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more Android DrawerLayout layout classes with side sliding function (1), please pay attention to the PHP Chinese website for related articles!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1676
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles