Android Fragment - SlidingMenu - ListActivity

时间:2013-04-25 19:27:22

标签: android android-fragments listactivity slidingmenu

所以我将slidingmenu(jfeinstein10)库添加到我的项目和菜单中。我遇到的问题是基于我的app扩展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扩展到Fragment。

下面是基于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;
}
}

由于

0 个答案:

没有答案