0

所以我将slidingmenu(jfeinstein10) 库添加到我的项目中并且菜单工作。我遇到的问题是基于我的应用扩展 ListActivity。

我已经看到了一些关于此的问题,并且大多数建议扩展到 Fragment 以使 Fragments 为菜单工作。我想知道是否有办法不使用 Fragments 来使菜单列表正常工作。

每次我移动到 SlidingFragmentActivity 或任何其他 Fragment Activity 时,onListItemClick 和其他方法都会开始中断。

下面是我的代码:

public class MainListActivity extends ListActivity {

public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
private SlidingMenu menu;

static final String KEY_TITLE = "title";
static final String KEY_AUTHOR = "author";
static final String KEY_IMAGE = "image";

ListView list;
LazyAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //setBehindContentView(R.layout.menu_frame);
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);

    menu = new SlidingMenu(this);
    menu.setMode(SlidingMenu.LEFT);
    menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    menu.setShadowWidth(5);
    menu.setFadeDegree(0.35f);
    menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
    menu.setBehindWidth(R.dimen.shadow_width);
    menu.setShadowDrawable(R.drawable.shadow);
    menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    menu.setMenu(R.layout.menu_frame);
    //getFragmentManager().beginTransaction().replace(R.id.menu_frame, new MenuFragment()).commit();

    if(isNetworkAvailable()){
        GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
        mProgressBar.setVisibility(View.VISIBLE);
        getBlogPostsTask.execute();
    }else{
        Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
    }
}


@Override
protected void onListItemClick(ListView l, View v, int position, long id){
    super.onListItemClick(l, v, position, id);
    try{
        JSONArray jsonPosts = mBlogData.getJSONArray("items");
        JSONObject jsonPost = jsonPosts.getJSONObject(position);
        String blogSummary = jsonPost.getString("summary");
        String blogUrl = jsonPost.getString("bitly");
        Intent intent = new Intent(this, BlogWebViewActivity.class);
        intent.setData(Uri.parse(blogSummary));
        intent.putExtra("mUrl",blogUrl);
        startActivity(intent);
    }catch(JSONException e){
        logException(e);
    }
}

private void logException(Exception e) {
    Log.e(TAG, "Exception caught!", e);
}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if(networkInfo != null && networkInfo.isConnected()){
        isAvailable = true;
    }
    return isAvailable;

}

public void handleBlogResponse() {
    mProgressBar.setVisibility(View.INVISIBLE);

    if(mBlogData == null){
        updateDisplayForError();
    }else{
        try {
            JSONArray jsonPosts = mBlogData.getJSONArray("items");
            ArrayList<HashMap<String,String>> blogPosts = new ArrayList<HashMap<String,String>>();
            for (int i=0;i<jsonPosts.length();i++){
                JSONObject post = jsonPosts.getJSONObject(i);
                String title = post.getString(KEY_TITLE);
                title = Html.fromHtml(title).toString();
                String tag = post.getString(KEY_AUTHOR);
                tag = Html.fromHtml(tag).toString();
                String image = post.getString(KEY_IMAGE);
                image = Html.fromHtml(image).toString();

                HashMap<String, String> blogPost = new HashMap<String,String>();
                blogPost.put(KEY_TITLE, title);
                blogPost.put(KEY_AUTHOR, tag);;
                blogPost.put(KEY_IMAGE, image);

                blogPosts.add(blogPost);
            }

            list=getListView();
            LazyAdapter adapter = new LazyAdapter(this, blogPosts);
            list.setAdapter(adapter);

        } catch (JSONException e) {
            logException(e);
        }
    }
}

private void updateDisplayForError() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(getString(R.string.error_title));
    builder.setMessage(getString(R.string.error_message));
    builder.setPositiveButton(android.R.string.ok,null);
    AlertDialog dialog = builder.create();
    dialog.show();

    TextView emptyTextView = (TextView) getListView().getEmptyView();
    emptyTextView.setText(getString(R.string.no_items));
}

private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject>{

    @Override
    protected JSONObject doInBackground(Object... params) {
        int responseCode = -1; 
        JSONObject jsonResponse = null;
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://www.domain.com/app_json.js");

        try {   
            HttpResponse response = client.execute(httpget);
            StatusLine statusLine = response.getStatusLine();
            responseCode = statusLine.getStatusCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while((line = reader.readLine()) != null){
                    builder.append(line);
                }
                jsonResponse = new JSONObject(builder.toString());
            }else{
                Log.i(TAG, "HTTP Failed: "+responseCode);
            }

        } catch (MalformedURLException e) {
            logException(e);
        } catch (IOException e) {
            logException(e);
        }
        catch(Exception e){
            logException(e);
        }
        return jsonResponse;


    }

    @Override
    protected void onPostExecute(JSONObject result){
        mBlogData = result;
        handleBlogResponse();
    }

}

@Override
public void onBackPressed() {
    if (menu.isMenuShowing()) {
        menu.showContent();
    } else {
        super.onBackPressed();
    }
}

}

我将菜单项作为字符串数组存储在 /values/array.xml 中。

我也设置了一个片段,但不知道如何在不从 ListActivity 扩展到片段的情况下访问它。

下面是我基于来自 github 的示例片段的片段:

public class MenuFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.menu_list, null);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    String[] colors = getResources().getStringArray(R.array.menu_items);
    ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(), 
            android.R.layout.simple_list_item_1, android.R.id.text1, colors);
    setListAdapter(colorAdapter);
}

@Override
public void onListItemClick(ListView lv, View v, int position, long id) {
    Fragment newContent = null;
    switch (position) {
    case 0:
        //newContent = new ColorFragment(R.color.red);
        break;
    case 1:
        //newContent = new ColorFragment(R.color.green);
        break;
    case 2:
        //newContent = new ColorFragment(R.color.blue);
        break;
    case 3:
        //newContent = new ColorFragment(android.R.color.white);
        break;
    case 4:
        //newContent = new ColorFragment(android.R.color.black);
        break;
    }
    if (newContent != null)
        switchFragment(newContent);
}

// the meat of switching the above fragment
private void switchFragment(Fragment fragment) {
    if (getActivity() == null)
        return;
}
}

谢谢

4

0 回答 0