Cannot customize Navigation Drawer

不羁的心 提交于 2020-01-05 14:10:54

问题


I need to customize my navigation drawer like following.

Currently I was able to add following part.

No matter how hard I tried to add another text fields, edit texts and images, I couldn't do it.

Here is my sample code.

This is how I added fields in strings.xml

 <string-array name="titles">
        <item>Hotel</item>
        <item>Historical Sites</item>
        <item>Shopping</item>
        <item>Restaurant</item>
        <item>Attractions</item>
        <item>wild Life</item>
        <item>Tour Service</item>
    </string-array>

    <array name="icons">
        <item>@drawable/ic_hotel</item>
        <item>@drawable/ic_historical</item>
        <item>@drawable/ic_shopping</item>
        <item>@drawable/ic_resturant</item>
        <item>@drawable/ic_attraction</item>
        <item>@drawable/ic_wildlife</item>
        <item>@drawable/ic_tourservices</item>
    </array>

Here is my mainactivity.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">

<!-- Framelayout to display Fragments -->
<FrameLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</FrameLayout>


<!-- Listview to display slider menu -->
<include layout="@layout/drawer_layout" />

Here is my list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:padding="5dp" >

        <ImageView
            android:id="@+id/icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            />

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@id/icon"
            android:gravity="center_vertical"
            android:textColor="#ffffff"
            android:textSize="20sp" />

        <CheckBox
            android:id="@+id/checkBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"/>

</RelativeLayout>

Here is my CustomAdapter.java

public class CustomAdapter extends BaseAdapter {
    Context context;  List<RowItem> rowItem;

    CustomAdapter(Context context, List<RowItem> rowItem) {
        this.context = context;
        this.rowItem = rowItem;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.list_item, null);
        }
        ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
        RowItem row_pos = rowItem.get(position);

        // setting the image resource and title
        imgIcon.setImageResource(row_pos.getIcon());
        txtTitle.setText(row_pos.getTitle());
        return convertView;
    }

    @Override
    public int getCount() {
        return rowItem.size();
    }

    @Override
    public Object getItem(int position) {
        return rowItem.get(position);
    }

    @Override
    public long getItemId(int position) {
        return rowItem.indexOf(getItem(position));
    }
}

Here is my mainactivity.java

public class Extract extends ActionBarActivity {

    String[] menutitles;
    TypedArray menuIcons;

    // nav drawer title
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private List<RowItem> rowItems;
    private CustomAdapter adapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extract);

        mTitle = mDrawerTitle = getTitle();
        menutitles = getResources().getStringArray(R.array.titles);
        menuIcons = getResources().obtainTypedArray(R.array.icons);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.slider_list);



        rowItems = new ArrayList<RowItem>();

        for (int i = 0; i < menutitles.length; i++) {
            RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(      i, -1));
            rowItems.add(items);
        }

        menuIcons.recycle();
        adapter = new CustomAdapter(getApplicationContext(), rowItems);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new SlideitemListener());

        // enabling action bar app icon and behaving it as toggle button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name)
        {
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }
            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();          }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);
        if (savedInstanceState == null) {
            // on first time display view for first nav item
            updateDisplay(0);
        }
    }

    class SlideitemListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updateDisplay(position);
        }
    }
        private void updateDisplay(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0:
                    fragment = new MapFragment();
                    break;

                case 1:
                    fragment = new hotel();
                    break;

                case 2:
                    fragment = new restaurant();
                    break;


                default:
                    break;
            }
            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();

                // update selected item and title, then close the drawer
                setTitle(menutitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
            }
            else {
                // error in creating fragment
                Log.e("Extract", "Error in creating fragment");
            }
        }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    @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_extract, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
            default :
                return super.onOptionsItemSelected(item);
        }
    }

    /***   * Called when invalidateOptionsMenu() is triggered   */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**   * When using the ActionBarDrawerToggle, you must call it during   * onPostCreate() and onConfigurationChanged()...   */
    @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);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}

Here is my drawer_layoout.xml

<?xml version="1.0" encoding="utf-8"?>
<DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/slider_list"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#000000"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:layout_weight="1" />

</DrawerLayout>

Please help me to add the image, two text views near image, horizontal line, and the edit text. Thanks in advance


回答1:


this will be the main layout that you will be using it contain two parts one is the main part which will have the layout of the main screen and the drawer_layout is the layout that has you navigation view layouts

So you will have to create drawer_layout as you want to display and just simply call it here

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/navigationDrawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/mainLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        // you will have layout that you will use for your main activity or the activity where you are showing your navigation View


    </FrameLayout>

    // the drawer_layout will define your navigation View 
    <include layout="@layout/drawer_layout" />

</android.support.v4.widget.DrawerLayout>

In the activity you will get access to your drawer_layout and get access to your views using that object like

DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.navigationDrawer);
// Example of getting your view object
ImageView yourImageView = (ImageView) drawerLayout.findViewById(R.id.imageView);
// you can access any your drawerView using that drawerLayout object



回答2:


In your MainActivity, add a new field for the LinearLayout, and assign value to it in onCreate()

private LinearLayout mLenear;

mLenear = (LinearLayout)findViewById(R.id.left_drawer);// inside onCreate

Then add following code inside onPrepareOptionsMenu

 @Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // if nav drawer is opened, hide the action items
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear);
    menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

Then change your closeDrawer like this.

mDrawerLayout.closeDrawer(mLenear);

This should resolve your issue. :)



来源:https://stackoverflow.com/questions/33690659/cannot-customize-navigation-drawer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!