导航抽屉 ListView 为空

Navigation Drawer ListView is empty

我有一个应用程序,第一个 activity 是登录页面。当用户成功登录时,他会看到他的项目。我正在使用 ListFragment 显示此列表(因为我还有 public 用户在登录页面的一半中看到的项目)。在他登录后,我在 activity 中添加了一个抽屉式导航。在经历了很多混乱之后,我能够在 activity 上添加抽屉式导航,但是它有一个空列表。

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:(扩展了 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>

另外,切换按钮也不起作用。我只看到一个后退箭头,点击它没有任何反应,我必须从左边滑动才能打开抽屉。

我建议您按照以下方式进行操作:

DrawerActivity中只创建导航抽屉,不使用onCreate(),而是使用onStart()onCreate() 将在扩展 DrawerActivity 的 activity 中调用,您将在那里调用 setContentView

您的 class 将如下所示:

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) {

    }
}

在每个 activity 中,您想要在其中使用 Drawer,您必须像当前 private_project_list.xml 一样构建布局,使用 DrawerLayout 作为主要容器,doby 布局您的 activity 作为第一个 child,导航抽屉布局作为第二个 child。然后,将 activity 扩展为 DrawerActivity.

Antoher 的建议是获取 DrawerActivity 中的列表,在其中调用 HttpGetHandler(),只有当数组已满时才必须设置适配器,否则传递给适配器一个空数组,因此列表将为空。

关于菜单按钮不显示

在 DrawerActivity 中似乎缺少一些操作栏的方法,尝试添加以下内容

@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);
    }