Navigation Drawer ListView is empty

2019-09-10 07:12发布

I have an app with the first activity being a log-in page. When the user successfully logs in he sees his projects. I am using ListFragment to diplay this list(since I also have public projects which the user sees in one-half of the login page). And I am adding a Navigation Drawer to the activity after he logs in. After a lot of confusion I was able to add the Navigation Drawer on the activity, but the it has an empty list.

DrawerActivity.java:

public class DrawerActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mScreenTitles;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.private_project_list);
    mTitle = mDrawerTitle = getTitle();
    mScreenTitles = getResources().getStringArray(R.array.screen_titles);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item, mScreenTitles));
    //mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_navigation_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}

/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // If the nav drawer is open, hide action items related to the content view
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {

    }
}

PrivateProjectListActivity.java: (which extends the DrawerActivity)

public class PrivateProjectListActivity extends DrawerActivity {
private final static String TAG_TITLE = "title";
private final static String TAG_ANIM_ARRAY_ID = "animation_array";
private final static String TAG_PROJECTS = "projects";
private final static String TAG_ID = "id";

JSONArray projects = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.private_project_list);
    new HttpGetHandler().execute();
}

private class HttpGetHandler extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... params) {
        String jsonUrl = "http://canvasflip.com/protected/actions/user.php?action=get-projects&network=Escort&index=0&count=100";
        HttpGet httpGet = new HttpGet(jsonUrl);
        try {
            HttpResponse httpResponse = MainActivity.httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream content = httpEntity.getContent();
            String result = convertToString(content);
            JSONObject jsonObject = new JSONObject(result);
            projects = jsonObject.getJSONArray(TAG_PROJECTS);
            PrivateProjectListActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try{
                        ArrayList<String> projectTitle = new ArrayList<String>();
                        ArrayList<String> imageId = new ArrayList<String>();
                        ArrayList<String> playId = new ArrayList<String>();
                        for(int i=0; i<projects.length(); i++) {
                            JSONObject p = projects.getJSONObject(i);
                            String title = p.getString(TAG_TITLE);
                            String id = p.getString(TAG_ID);
                            String array_anim_id = p.getString(TAG_ANIM_ARRAY_ID);
                            String imgId = array_anim_id.substring(0, 4);
                            projectTitle.add(title);
                            imageId.add(imgId);
                            playId.add(id);
                        }
                        String[] arrProjectTitle = new String[projectTitle.size()];
                        String[] arrImageId = new String[imageId.size()];
                        final String[] pid = new String[playId.size()];
                        for(int i = 0; i<projectTitle.size(); i++)
                            arrProjectTitle[i] = projectTitle.get(i);
                        for(int j = 0; j<imageId.size(); j++)
                            arrImageId[j] = imageId.get(j);
                        for(int k = 0; k<playId.size(); k++)
                            pid[k] = playId.get(k);

                        Bundle b = new Bundle();
                        b.putStringArray("projectTitle", arrProjectTitle);
                        b.putStringArray("imageId", arrImageId);
                        PrivateProjectsListFragment fragment = new PrivateProjectsListFragment();
                        fragment.setArguments(b);

                        FragmentManager fm = getFragmentManager();
                        FragmentTransaction ft = fm.beginTransaction();
                        ft.replace(R.id.privateProjectsContainer,fragment);
                        ft.commit();
                    }catch(Exception e) {

                    }
                }
            });
        }catch(Exception e) {
        }
        return null;
    }

    public String convertToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine())!=null) {
            result += line;

        }
        inputStream.close();
        return result;
        }
    }
}

private_project_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="@+id/privateProjectsContainer"
android:background="#eeeeee">


</FrameLayout>

<ListView
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#111"/>
    </android.support.v4.widget.DrawerLayout>

Plus , the toggle button is also not working. I only see a back arrow , and nothing happens on clicking it , I have to slide from the left to open the drawer.

1条回答
forever°为你锁心
2楼-- · 2019-09-10 08:07

I suggest to you to do it like following:

In the DrawerActivity, create only the navigation drawer, without using onCreate(), but using onStart(). The onCreate() will be called in the activity that extends DrawerActivity and there you'll call setContentView

Your class will look like so:

public class DrawerActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mScreenTitles;

@Override
    protected void onStart(){
        super.onStart();
        mTitle = mDrawerTitle = getTitle();
        mScreenTitles = getResources().getStringArray(R.array.screen_titles);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mScreenTitles));
        //mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_navigation_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
}

/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // If the nav drawer is open, hide action items related to the content view
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {

    }
}

In every activity in which you want to use the Drawer, you have to build you layout like you current private_project_list.xml, using DrawerLayout as main container, the doby layout of your activity as its first child and the navigation drawer layout as second child. Then, extends the activity to DrawerActivity.

Antoher suggestion is to get the list in teh DrawerActivity, calling HttpGetHandler() inside of it, you have to set the adapter only when the array will be full, otherwise you pass to the adapter an empty array, so the list will be empty.

About the menu button not displayed

In DrawerActivity seems missing some methods for the action bar, try add the following

@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);
    }
查看更多
登录 后发表回答