10

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.

4 Answers4

18

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)
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Is there a way to switch between Activities and have the sliding drawer to smoothly disappear with a transition? – Konsumierer Jun 06 '13 at 14:36
  • @Konsumierer this might be a bit late for you, but you want to close the drawer and then start your new activity. – buczek Jul 15 '13 at 17:01
  • 1
    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? – M Rajoy Aug 13 '13 at 11:35
  • 1
    @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. – CommonsWare Aug 13 '13 at 11:39
  • @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: http://stackoverflow.com/questions/17604423/replacing-call-to-setimageresource-with-setimagebitmap-to-reduce-hiccup – CrimsonX Aug 14 '13 at 22:03
  • Are they any examples / existing source code that update the UI without fragments? – blub Sep 30 '13 at 09:06
  • @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... – Rishabh Srivastava Jan 23 '14 at 10:14
  • @RishabhSrivastava, you can use BaseActivity, for example, http://stackoverflow.com/questions/19442378/navigation-drawer-to-switch-activities-instead-of-fragments. – CoolMind Nov 30 '16 at 09:16
  • 1
    @CoolMind The project ended 2 years ago :D – Rishabh Srivastava Nov 30 '16 at 10:27
  • @RishabhSrivastava, and how have you done it? :D What method have you used? – CoolMind Nov 30 '16 at 10:41
  • https://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 – Rishabh Srivastava Nov 30 '16 at 11:39
  • @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. – CoolMind Nov 30 '16 at 12:02
  • @CoolMind In case you're still looking to create with Activities: http://stackoverflow.com/a/19451842/2767703. I use this in all my projects – Kevin van Mierlo Feb 27 '17 at 13:55
  • @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 https://github.com/karnamsupreeth/drawersample (there is one small (already closed) issue when building a project). – CoolMind Feb 27 '17 at 15:45
  • 1
    @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! – Kevin van Mierlo Feb 27 '17 at 16:43
3

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);
FloatOverflow
  • 791
  • 9
  • 9
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>
Volverine
  • 75
  • 10
2

use this code

private void selectItem(int position) {


    // Locate Position
    switch (position) {
    case 0:
            startActivity(new Intent(this,TEST.class));
        break;
MAX
  • 31
  • 3