Complete and detailed examples of Android slide menus (Basic edition) and android examples

Source: Internet
Author: User

Complete and detailed examples of Android slide menus (Basic edition) and android examples
MainActivity is as follows:

Package cc. cd; import android. OS. asyncTask; import android. OS. bundle; import android. util. log; import android. view. motionEvent; import android. view. velocityTracker; import android. view. view; import android. view. view. onTouchListener; import android. view. windowManager; import android. widget. linearLayout; import android. app. activity; import android. content. context;/*** Demo Description: * a simple example of a slide menu SlidingMenu * is displayed in a Activ Note: * in this example, there are two interfaces, menu and content. the content page is displayed when you enter the application. * If your finger slides to the right of the screen, the menu and hidden content are displayed. likewise. * To display and hide a menu, modify leftMargin in LayoutParams of the menu to achieve the effect. ** steps: * 1. during initialization, set leftMargin in LayoutParams of menu to completely hide it. * 2 set Touch listening for content. * 3 during the move process, the leftMargin in the LayoutParams of the menu is constantly modified to display or hide the leftMargin in * 4 when the menu is up, the asynchronous task AsyncTask is used to modify the leftMargin in the LayoutParams of the menu. * completely display or hide the menu. ** the above routines are quite common. See. ** reference: * 1 http://blog.csdn.net/guolin_blog/article/details/8714621 * 2 http://blog.csdn.net/hudashi/article/details/7352157 * Thank you very much ** Note: * 1 the image used in the example also comes from reference 1*2 for simplified logic, the two interfaces in the example are not the actual View Interface */public class MainActivity extends Activity {private int screenWidth; private View contentView; private View menuView; private float xDown; private float xMove; private float xUp ;// When the menu is fully displayed, the minimum width of content is private int contentViewMinWidth = 80; // indicates whether the menu is visible. This value is invalid during sliding. // This value is changed only when the menu is fully displayed or hidden after sliding. private boolean isMenuVisible = false; private int menuParamsMaxLeftMargin = 0; private int menuParamsMinLeftMargin = 0; // speed tracking private VelocityTracker mVelocityTracker; // public static final int VELOCITY_THRESHOLD = 200; // TAG private final static String TAG = "MainActivity"; // menu layout L AyoutParams private LinearLayout. layoutParams menuLayoutParams; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); init ();} private void init () {// obtain the screen width WindowManager windowManager = (WindowManager) getSystemService (Context. WINDOW_SERVICE); screenWidth = windowManager. getdefadisplay display (). getWidth (); // initialize contentViewcontentView = findV IewById (R. id. contentLinearLayout); // set the width of contentView to the width of the screen contentView. getLayoutParams (). width = screenWidth; // set Touch to listen to contentView. setOnTouchListener (new TouchListenerImpl (); // initialize menuViewmenuView = findViewById (R. id. menuLinearLayout); menuLayoutParams = (LinearLayout. layoutParams) menuView. getLayoutParams (); // set the width of the menuView. // set its width to screen width minus the minimum width of contentView menuLayoutParams. width = screenWidth-contentViewMinW Idth; // The menuView is completely hidden during initialization. menuParamsMinLeftMargin =-menuLayoutParams. width; menuLayoutParams. leftMargin = menuParamsMinLeftMargin;}/*** details about distanceX in ACTION_MOVE. * The distanceX value increases or decreases continuously during a sliding process (from the finger to the finger. * Because int distanceX = (int) (xMove-xDown); * This xDown is the coordinate value of the press, during the Moving process, when distanceX is calculated, the X down minus the xMove at each time point is always used. that is, the xDown remains unchanged during the sliding process, while the xMove is constantly * Changing. * Code Description: * if (isMenuVisible) {* menuLayoutParams. lef TMargin = distanceX; *} else {* menuLayoutParams. leftMargin = menuParamsMinLeftMargin + distanceX; *} * The menu is hidden at the beginning. press your finger and slide to the right of the screen. call: * menuLayoutParams. leftMargin = menuParamsMinLeftMargin + distanceX; * This menuLayoutParams. leftMargin is constantly increasing until 0 (pay attention to cross-border judgment). At this time, * menuView is fully displayed. then press your finger and slide to the left of the screen. call: * menuLayoutParams. leftMargin = distanceX; * The negative number distanceX has been decreasing, which is menuLayoutParams. value of leftMargin until * menuView is completely hidden The value of this parameter is menuParamsMinLeftMargin ). ** this problem is not difficult, but it should be noted here to prevent further response. */private class TouchListenerImpl implements OnTouchListener {@ Overridepublic boolean onTouch (View v, MotionEvent event) {// startVelocityTracker (event); switch (event. getAction () {case MotionEvent. ACTION_DOWN: xDown = event. getRawX (); break; case MotionEvent. ACTION_MOVE: xMove = event. getRawX (); int distanceX = (int) (xMove-xDown); Lo G. I (TAG, "xDown =" + xDown + ", xMove =" + xMove + ", distanceX =" + distanceX); if (isMenuVisible) {menuLayoutParams. leftMargin = distanceX;} else {menuLayoutParams. leftMargin = menuParamsMinLeftMargin + distanceX;} // if (menuLayoutParams. leftMargin <menuParamsMinLeftMargin) {menuLayoutParams. leftMargin = menuParamsMinLeftMargin;} if (menuLayoutParams. leftMargin> menuParamsMaxLeftMargin) {menuLayoutParams. leftMargin = menu ParamsMaxLeftMargin;} // set the LayoutParamsmenuView of the menuView. setLayoutParams (menuLayoutParams); break; case MotionEvent. ACTION_UP: xUp = event. getRawX (); // determine the gesture intention to display menuif (wantToShowMenu () {// determine whether to display menuif (shouldScrollToMenu () {scrollToMenu ();} else {scrollToContent () ;}/// determine the intent of the gesture to display contentif (wantToShowContent () {// determine whether to display contentif (shouldScrollToContent () {scrollToContent ();} else {scrollToMenu () ;}// termination speed Tracking stopVelocityTracker (); break; default: break;} return true;}/*** determine whether the current gesture wants to display the Menu * judgment condition: * 1 lift coordinates greater than pressing coordinates * 2 menu itself invisible */private boolean wantToShowMenu () {return (xUp-xDown> 0 )&&(! IsMenuVisible);}/*** determines whether the menu should be completely displayed * judgment condition: * sliding distance greater than 1/2 of the screen * or sliding speed greater than the speed threshold VELOCITY_THRESHOLD */private boolean shouldScrollToMenu () {return (xUp-xDown> screenWidth/2) | (getScrollVelocity ()> VELOCITY_THRESHOLD);}/*** scroll the screen to the menu. displays the complete menu. * modify leftMargin */private void scrollToMenu () {new scrollasynctask(cmd.exe cute (30 );} /*** determine whether the current gesture wants to display the menu Content * judgment condition: * 1 lift the coordinate less than the press Coordinates * 2 menu itself are visible */private boolean wantToShowContent () {return (xUp-xDown <0) & (isMenuVisible ));} /*** determine whether the content should be completely displayed * judgment condition: * xDown-xUp + contentViewMinWidth greater than 1/2 of the screen * or sliding speed greater than the speed threshold VELOCITY_THRESHOLD */private boolean shouldScrollToContent () {return (xDown-xUp + contentViewMinWidth> screenWidth/2) | (getScrollVelocity ()> VELOCITY_THRESHOLD);}/*** scroll the screen to the content. the entire content is displayed. * The L of the menu is continuously modified at the speed of-30. LeftMargin */private void scrollToContent () {new scrollasynctask(.exe cute (-30);}/*** Start Speed Tracing */private void startVelocityTracker (MotionEvent event) {if (mVelocityTracker = null) {mVelocityTracker = VelocityTracker. obtain ();} mVelocityTracker. addMovement (event);}/*** get the finger sliding speed X on the content */private int getScrollVelocity () {// set the VelocityTracker unit. 1000 indicates the pixel mVelocityTracker that moves within 1 second. computeCurr EntVelocity (1000); // obtain the value of the moving pixel in the X direction within 1 second. int xVelocity = (int) mVelocityTracker. getXVelocity (); return Math. abs (xVelocity);}/*** end speed tracking */private void stopVelocityTracker () {if (mVelocityTracker! = Null) {mVelocityTracker. recycle (); mVelocityTracker = null ;}} /*** modify leftMargin in LayoutParams of menu continuously using asynchronous tasks to achieve a * view moving effect */private class ScrollAsyncTask extends AsyncTask <Integer, Integer, integer >{@ Overrideprotected Integer doInBackground (Integer... speed) {int leftMargin = menuLayoutParams. leftMargin; while (true) {// speedleftMargin = leftMargin + speed [0] for each change; // if this parameter is exceeded, the process is out of bounds and out of the loop if (leftMargin> menuParamsMaxLeftMargin) {leftMargin = menuParamsMaxLeftMargin; break;} // if it is out of bounds, the process is out of bounds and out of the loop if (leftMargin <menuParamsMinLeftMargin) {leftMargin = menuparamsminleftmar ;} // publishProgress (leftMargin) for updating the notification progress; // The Thread sleeps for 25 milliseconds to facilitate scrolling. try {Thread. sleep (25);} catch (Exception e) {}} // set the flag isMenuVisibleif (speed [0]> 0) {isMenuVisible = true ;} else {isMenuVisible = false;} return leftMargin;} @ Overrideprotected void onProgressUpdate (Integer... leftMargin) {super. onProgressUpdate (leftMargin); menuLayoutParams. leftMargin = leftMargin [0]; menuView. setLayoutParams (menuLayoutParams);} @ Overrideprotected void onPostExecute (Integer leftMargin) {super. onPostExecute (leftMargin); menuLayoutParams. leftMargin = leftMargin; menuView. setLayoutParams (menuLayoutParams );}}}

Main. xml is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <LinearLayout        android:id="@+id/menuLinearLayout"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="@drawable/menu"        android:orientation="vertical" />    <LinearLayout        android:id="@+id/contentLinearLayout"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="@drawable/content"        android:orientation="vertical" /></LinearLayout>



Now, is it better for android to use the SlidingMenu open-source project to slide the menu bar, or is it better to use the Navigation Drawer that comes with android?

If you are learning the code, it is recommended to study the official version. However, SlidingMenu has many functions, such as controlling the background behind the menu when sliding out. It seems that the background of Navigation Drawer cannot be moved. It is a trend to replace open-source projects with official APIs, because everyone thinks that official interfaces are safe to use, but open-source projects may be more flexible.

Android slide menu Background Brightness and transparency settings

Without such an api, you can make the transparency by yourself. Just like the animation effect, you can define an xml file. To adjust the brightness, modify settings. For example, when you slide, you need to increase the brightness to 100, Settings. system. putInt (getContentResolver (), Settings. system. SCREEN_BRIGHTNESS, 100); After sliding, the brightness changes to 100 immediately, instead of gradually becoming brighter. You can adjust the value of 100 according to the sliding speed. If not, you may need to add the settings modification permission in AndroidManifest. xml, but 4.4 does not seem to require

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.