片段选项卡未显示

时间:2013-10-28 06:44:21

标签: java android android-fragments fragment-tab-host

在我的程序中,我显示多级Listview,但每当我调用另一个Activity时,片段选项卡都没有出现。

我正在使用这个很棒的教程:http://www.androidbegin.com/tutorial/android-actionbarsherlock-viewpager-tabs-tutorial/

见下图,第一级列表视图:

enter image description here

第二级 ListView:

enter image description here

ListCategoryFragment.xml: -

 public class ListCategoryFragment extends SherlockFragment implements OnItemClickListener {

    ListView lview3;
    ListCategoryAdapter adapter;

    private ArrayList<Object> itemList;
    private ItemBean bean;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Get the view from fragmenttab1.xml
        View view = inflater.inflate(R.layout.fragment_category_tab, container, false);
        prepareArrayList();
        lview3 = (ListView) view.findViewById(R.id.listView1);
        adapter = new ListCategoryAdapter(getActivity(), itemList);
        lview3.setAdapter(adapter);
        lview3.setOnItemClickListener(this);

    return view;
}

private static final int categoryFirst = 0;
private static final int categorySecond = 1;
private static final int categoryThird = 2;

public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {

    // Set up different intents based on the item clicked: 
    switch (position)
    {
        case categoryFirst:
         Intent intent1 = new Intent(getActivity(), ListItemActivity.class);
         intent1.putExtra("category", "Category - 1");
         startActivity(intent1);    
         break;

        case categorySecond:
         Intent intent2 = new Intent(getActivity(), ListItemActivity.class);
         intent2.putExtra("category", "Category - 2");
         startActivity(intent2);    
         break;

        case categoryThird:
         Intent intent3 = new Intent(getActivity(), ListItemActivity.class);
         intent3.putExtra("category", "Category - 3");
         startActivity(intent3);    
         break;

        default:
         break;
    }
}

public void prepareArrayList()
{
    itemList = new ArrayList<Object>();

    AddObjectToList("Category - 1");
    AddObjectToList("Category - 2");
    AddObjectToList("Category - 3");
}

// Add one item into the Array List
public void AddObjectToList(String title)
{
    bean = new ItemBean();
    bean.setTitle(title);
    itemList.add(bean);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    setUserVisibleHint(true);
}

}

ListItemActivity.java: -

public class ListItemActivity extends SherlockFragmentActivity {


static String URL = "http://www.site.url/tone.json";

static String KEY_CATEGORY = "item";
static final String KEY_TITLE = "title";

ListView list;
ListItemAdapter adapter;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    getActionBar().setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.activity_item_list);

    final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
    list = (ListView) findViewById(R.id.listView1);
    adapter = new ListItemAdapter(this, itemsList);
    list.setAdapter(adapter);

    Bundle bdl = getIntent().getExtras();
    KEY_CATEGORY = bdl.getString("category");

    if (isNetworkAvailable()) {
        new MyAsyncTask().execute();
    } else {

        AlertDialog alertDialog = new AlertDialog.Builder(ListItemActivity.this).create();
        alertDialog.setMessage("The Internet connection appears to be offline.");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alertDialog.show();
    }
}

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.main, menu);

    return super.onCreateOptionsMenu(menu);
}

 private Intent getDefaultShareIntent(){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
        intent.putExtra(Intent.EXTRA_TEXT, "TEXT");
        startActivity(Intent.createChooser(intent, "Share via"));
        return intent;
    }

/** The event listener for the Up navigation selection */
@Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {

    switch(item.getItemId())
    {
        case android.R.id.home:
            finish();
            break;

        case R.id.menu_item_share:
            getDefaultShareIntent();
            break; 
    }
    return true;
}

private boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return (info != null);
}

class MyAsyncTask extends
        AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
    private ProgressDialog progressDialog = new ProgressDialog(
            ListItemActivity.this);

    @Override
    protected void onPreExecute() {
        progressDialog.setMessage("Loading, Please wait.....");
        progressDialog.show();
    }

    final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(
            String... params) {
        HttpClient client = new DefaultHttpClient();
        // Perform a GET request for a JSON list
        HttpUriRequest request = new HttpGet(URL);
        // Get the response that sends back
        HttpResponse response = null;
        try {
            response = client.execute(request);
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // Convert this response into a readable string
        String jsonString = null;
        try {
            jsonString = StreamUtils.convertToString(response.getEntity()
                    .getContent());
        } catch (IllegalStateException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // Create a JSON object that we can use from the String
        JSONObject json = null;
        try {
            json = new JSONObject(jsonString);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {

            JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);

            for (int i = 0; i < jsonArray.length(); i++) {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
                itemsList.add(map);
            }
            return itemsList;
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return null;
    }


    @Override
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        list = (ListView) findViewById(R.id.listView1);
        adapter = new ListItemAdapter(ListItemActivity.this, itemsList);
        list.setAdapter(adapter);

        TextView lblTitle = (TextView) findViewById(R.id.text);
        lblTitle.setText(KEY_CATEGORY);

        this.progressDialog.dismiss();
        list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                HashMap<String, String> map = itemsList.get(position);

                Intent in = new Intent(ListItemActivity.this, ListItemDetailActivity.class);
                in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
                startActivity(in);                  
            }
        });
    }
}

}

1 个答案:

答案 0 :(得分:1)

这是正常行为,因为您正从片段活动转移到正常活动。但只有你的第一个活动有标签。

执行此操作的正确方法是删除意图和新活动。相反,它应该用片段本身替换。

例如,在列表项单击中,停止将Intent调用到新的片段活动,并将其替换为调用片段本身。

只有一个Activity,它将是持有标签的那个,所有其他的应该是片段。您只需要在同一活动中替换片段。