آموزش برنامه نویسی در مشهد

ساخت Navigation Drawer در اندروید

در این مقاله ساخت Navigation Drawer در اندروید ، یاد خواهیم گرفت که چگونه از یک ” Navigation Drawer” برای اکتیویتی های مختلف استفاده کنیم. Navigation Drawer یک ویجت مهم در اپلیکیشن اندروید است که بر اساس انتخاب کاربر Fragments های Navigation در هنگام بارگذاری بصورت صفحه های مختلفی مشاهده می شوند. اما گاهی اوقات ، استفاده از Fragments با  Navigation می تواند باعث ایجاد مشکلاتی شود. به جای استفاده از Fragment ها، ما می توانیم از روش پایین که بسیار ساده است بهره بگیریم.

این روش  به مراحل زیر تقسیم نموده ام.

مرحله ۱: یک پروژه جدید را با Navigation Drawer Activity ایجاد کنید.
مرحله ۲: یک BaseActivity که از AppCompatActivity ارث بری دارد را ایجاد نمایید.
مرحله ۳: اکتیوتی ها بعد را  با استفاده از ارث بری از BaseActivity ایجاد کنید.
مرحله ۴: از منوی عملیات ، قابلیت هایی را به Navigation بیافزایید.

بدون هیچ مقدمه ای دیگر، وارد قسمت کد نویسی می شویم.

 

مرحله ۱ – ساخت navigation drawer در اندروید :

۱٫ Android Studio را باز کرده و یک پروژه جدید ایجاد کنید.
۲٫ نامی دلخواه را به عنوان نام پروژه خود انتخاب کنید و Navigation Drawer activity را انتخاب کنید.

.

۳٫ برای ایجاد یک پروژه جدید در Android Studio، روی دکمه Finish کلیک کنید.

مرحله  2 – ساخت navigation drawer در اندروید :

۱- در این مرحله، Navigation Drawer activity را به BaseActivity تغییر نام می دهیم. به عنوان مثال، من “MainActivity” را به “BaseActivity” تغییر نام دادم.

۲- بخش پیش فرض کدگذاری در BaseActivity را ، بصورتی که در زیر نشان داده شده است تغییر دهید.

بخش کدنویسی :

     فایل content_main.xml را ایجاد کنید و FrameLayout را همانطوری که در زیر نشان داده شده است به عنوان Parent Layout اضافه کنید. این Frame Layout برای اتصال و ارتباط children layouts مورد استفاده قرار می گیرد.

<?xml version="1.0" encoding="utf-8"?>  
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/content_frame"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="com.androidmads.navdraweractivity.BaseActivity"  
    tools:showIn="@layout/app_bar_main" />

 

در اینجا، FrameLayout دارای یک id با نام “content_frame” می باشد .

فایل BaseActivity.java خود را باز کنید و کد زیر را اضافه کنید. در اینجا، activity_main.xml برای content_main.xml استفاده شده است.

public class BaseActivity extends AppCompatActivity  
 implements NavigationView.OnNavigationItemSelectedListener {  
  
// Declaration  
DrawerLayout drawer;  
FloatingActionButton fab;  
NavigationView navigationView;  
  
@Override  
protected void onCreate(Bundle savedInstanceState) {  
 super.onCreate(savedInstanceState);  
 setContentView(R.layout.activity_main);  
   
 // Initialize Widgets  
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
 setSupportActionBar(toolbar);  
  
 fab = (FloatingActionButton) findViewById(R.id.fab);  
 drawer = (DrawerLayout) findViewById(R.id.drawer_layout);  
 ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);  
 drawer.setDrawerListener(toggle);  
 toggle.syncState();  
   
 navigationView = (NavigationView) findViewById(R.id.nav_view);  
 navigationView.setNavigationItemSelectedListener(this);  
}  
  
@SuppressWarnings("StatementWithEmptyBody")  
@Override  
public boolean onNavigationItemSelected(@NonNull MenuItem item) {  
 int id = item.getItemId();  
 if (id == R.id.nav_activity1) {  
  startAnimatedActivity(new Intent(getApplicationContext(), FirstActivity.class));  
 } else if (id == R.id.nav_activity2) {  
  startAnimatedActivity(new Intent(getApplicationContext(), SecondActivity.class));  
 }  
  
 drawer = (DrawerLayout) findViewById(R.id.drawer_layout);  
 drawer.closeDrawer(GravityCompat.START);  
 return true;  
}

 

در اینجا، StartAnimatedActivity (اینتنت) برای شروع فعالیتی با انیمیشن مورد استفاده قرار می گیرد.

مرحله ۲

۱- یک  Activity جدید ایجاد کرده و برای آن نامی انتخاب کنید . والد این کلاس را از AppCompatActivity به BaseActivity تغییر دهید.
۲- بار دیگر، یک  Activity جدید  ایجاد کرده و آن را  نامگذاری کنید. والد این کلاس را از AppCompatActivity به BaseActivity تغییر دهید.

مرحله ۳

۱-همانطور که در زیر نشان داده شده است SetContentView را در متد onCreate فایل های ایجاد شده در مرحله ۲ جایگزین کنید.

بخش کد نویسی :

setContentView(R.layout.activity_first)  
To   
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
//inflate your activity layout here!  
@SuppressLint("InflateParams")  
View contentView = inflater.inflate(R.layout.activity_first, null, false);  
drawer.addView(contentView, 0);

 

در اینجا لایوت activity_first.xml ،  برای فعالیت FirstActivity.java می باشد. از این روش برای مشخص کردن لایوت در BaseActivity استفاده می شود.
کد کامل برای FirstActivity.java

public class FirstActivity extends BaseActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
        //inflate your activity layout here!  
        @SuppressLint("InflateParams")  
        View contentView = inflater.inflate(R.layout.activity_first, null, false);  
        drawer.addView(contentView, 0);  
        navigationView.setCheckedItem(R.id.nav_activity1);  
        fab.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                Snackbar.make(view, "Hello First Activity", Snackbar.LENGTH_LONG)  
                        .setAction("Action", null).show();  
            }  
        });  
  
    }  
  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        // Inflate the menu; this adds items to the action bar if it is present.  
        getMenuInflater().inflate(R.menu.menu_first, menu);  
        return true;  
    }  
  
    @Override  
    public boolean onOptionsItemSelected(MenuItem item) {  
        // Handle action bar item clicks here. The action bar will  
        // automatically handle clicks on the Home/Up button, so long  
        // as you specify a parent activity in AndroidManifest.xml.  
        int id = item.getItemId();  
  
        //noinspection SimplifiableIfStatement  
        if (id == R.id.action_menu_first) {  
            return true;  
        }  
  
        return super.onOptionsItemSelected(item);  
    }  
  
    @Override  
    public void onBackPressed() {  
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);  
        if (drawer.isDrawerOpen(GravityCompat.START)) {  
            drawer.closeDrawer(GravityCompat.START);  
        } else {  
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {  
                finishAffinity();  
            } else {  
                super.onBackPressed();  
            }  
        }  
    }  
}

 

در اینجا، من از متد onBackPressed برای بستن DrawerLayout و بستن اپلیکیشن استفاده کرده ام .

به این ترتیب، می توانید از NavigationView مشابهی برای تمام فعالیت ها استفاده کنید. همچنین می توانیم فعالیت های دیگری را با همان رویکرد برای نمایش NavigationView ایجاد کنیم.

نکته:

      فراموش نکنید که launcher activity خود را به FirstActivity تغییر دهید.

دانلود پروژه ساخت Navigation Drawer در اندروید

دانلود پروژه

 

خروج از نسخه موبایل