How can I use the Navigation Drawer without fragments?

23,274

Solution 1

First, API 10 has access to fragments via the same Android Support package that contains the DrawerLayout. This has been around for over two years, and you should not be trying to mess with new things like DrawerLayout if you are unfamiliar with what Android has had for the past two years.

Second, there is nothing with DrawerLayout that is tied to fragments. Quoting the Web page that you linked to:

When the user selects an item in the drawer's list, the system calls onItemClick() on the OnItemClickListener given to setOnItemClickListener(). What you do in the onItemClick() method depends on how you've implemented your app structure.

If you read those two sentences closely, you will see that the word "fragment" appears in neither of them. That is because DrawerLayout is not tied to fragments. The sample code they show uses fragments, but that is merely sample code.

Hence, you are welcome to update your UI however you want:

  • execute a FragmentTransaction using the Android Support package's backport of fragments, or
  • start an activity, or
  • call setContentView() again on your existing activity, or
  • otherwise modify the UI of the existing activity (e.g., hide/show some widgets)

Solution 2

You may use also LayoutInflater class.

  1. Create xml layout file.
  2. Find the View to change using findViewById.
  3. Remove all children from the found View using .removeAllViews() method.
  4. Inflate xml layout content into found View using .inflate() method.

This is an example:

LinearLayout layoutToChange = (LinearLayout)findViewById(R.id.layout_to_change);
layoutToChange.removeAllViews();

LayoutInflater inflater = LayoutInflater.from(this);
LinearLayout newLayout = (LinearLayout)inflater.inflate(R.layout.new_layout, null);

layoutToChange.addView(newLayout);

Solution 3

basic drawer without fragment

package xxxxxx;


import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;

import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;




public class loginhome extends AppCompatActivity {

    private ListView mDrawerList;
    private DrawerLayout mDrawerLayout;
    private ArrayAdapter<String> mAdapter;
    private ActionBarDrawerToggle mDrawerToggle;
    private String mActivityTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginhome);
        Toolbar topToolBar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(topToolBar);
        mDrawerList = (ListView)findViewById(R.id.navList);
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        mActivityTitle = getTitle().toString();

        addDrawerItems();
        setupDrawer();


        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

    }

    private void addDrawerItems() {
        String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
        mAdapter = new ArrayAdapter<String>(this, R.layout.drawer_items,R.id.label ,osArray);
        mDrawerList.setAdapter(mAdapter);

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(loginhome.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupDrawer() {
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle("Navigation!");
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mActivityTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        mDrawerToggle.setDrawerIndicatorEnabled(true);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    @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 onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, 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_help) {
            Toast.makeText(loginhome.this, "setting", Toast.LENGTH_LONG).show();
        }
        if(id == R.id.action_place){
            Toast.makeText(loginhome.this, "Refresh App", Toast.LENGTH_LONG).show();
        }
        if(id == R.id.action_search){
            Toast.makeText(loginhome.this, "Create Text", Toast.LENGTH_LONG).show();
        }
        // Activate the navigation drawer toggle
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

draweritems.xml

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


        <TextView
            android:id="@+id/label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:textSize="30sp"
            android:background="#D3D3D3">
        </TextView>
    </LinearLayout>

toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"


        >

    </android.support.v7.widget.Toolbar>

Solution 4

use this code

private void selectItem(int position) {


    // Locate Position
    switch (position) {
    case 0:
            startActivity(new Intent(this,TEST.class));
        break;
Share:
23,274
Admin
Author by

Admin

Updated on March 04, 2020

Comments

  • Admin
    Admin about 4 years

    I'm trying to follow this tutorial on how to create a Navigation Drawer, but I don't want to use Fragments to show new content after the user select an item from the drawer list. What's the best aproach to get around this problem? I'm using API 10 which doesn't implements Fragments.

  • Konsumierer
    Konsumierer almost 11 years
    Is there a way to switch between Activities and have the sliding drawer to smoothly disappear with a transition?
  • buczek
    buczek almost 11 years
    @Konsumierer this might be a bit late for you, but you want to close the drawer and then start your new activity.
  • Gabriel Sanmartin
    Gabriel Sanmartin over 10 years
    Is using fragments a better solution though? You avoid recreating the action bar & navigation drawer if you want them in all of your app screens, don't you?
  • CommonsWare
    CommonsWare over 10 years
    @kelmer: "Is using fragments a better solution though?" -- that depends upon your definition of "better" and your specific use case. For example, if you want multiple entry points into your app from outside the app, most likely you will want multiple activities for that. "You avoid recreating the action bar" -- you will still have the same amount of code, as you still need to define the action bar and how it changes as your visible fragment mix changes. "& navigation drawer" -- this can be handled via other reuse techniques, such as a static helper method.
  • Milos Vidakovic
    Milos Vidakovic over 10 years
    @Konsumierer: if you're looking to smooth out the animation of the sliding drawer, you need to investigate using async tasks to perform long running operations outside of the UI thread. You have to be very careful when doing this or you can introduce race conditions - see my question and answer here: stackoverflow.com/questions/17604423/…
  • blub
    blub over 10 years
    Are they any examples / existing source code that update the UI without fragments?
  • Rishabh Srivastava
    Rishabh Srivastava over 10 years
    @CommonsWare but if we use activity instead of fragment and click on drawer item a new activity is opened and from that activity the drawer is inaccessible i.e. it doesn't work...
  • CoolMind
    CoolMind over 7 years
    @RishabhSrivastava, you can use BaseActivity, for example, stackoverflow.com/questions/19442378/….
  • Rishabh Srivastava
    Rishabh Srivastava over 7 years
    @CoolMind The project ended 2 years ago :D
  • CoolMind
    CoolMind over 7 years
    @RishabhSrivastava, and how have you done it? :D What method have you used?
  • Rishabh Srivastava
    Rishabh Srivastava over 7 years
    github.com/jfeinstein10/SlidingMenu. I used this library and modified it a lot. Till the core. I will suggest to use fragments because doing this will show a lot in the performance of the app. @CoolMind
  • CoolMind
    CoolMind over 7 years
    @RishabhSrivastava, thanks! I have already made an app with fragments, but eager to avoid them. They produce many difficult situations, so I want to make it with activities.
  • Kevin van Mierlo
    Kevin van Mierlo about 7 years
    @CoolMind In case you're still looking to create with Activities: stackoverflow.com/a/19451842/2767703. I use this in all my projects
  • CoolMind
    CoolMind about 7 years
    @KevinvanMierlo, thanks, I saw your project. Yes, probably will modernize a project from fragments to activities, it will help with some design problems. Also saw at github.com/karnamsupreeth/drawersample (there is one small (already closed) issue when building a project).
  • Kevin van Mierlo
    Kevin van Mierlo about 7 years
    @CoolMind That one also looks good. Also one tip: When the drawer is closing fade the content view (I always give it id @+id/content) and then when new activity is started fade in. This way it looks better. Good luck!