0

我在片段内实现列表视图时遇到了一些麻烦,我使用 [ActionBarSherlock Side Menu Navigation Drawer][1]

[1]:http ://www.androidbegin.com/tutorial/implementing-actionbarsherlock-side-menu-navigation-drawer-in-android/来自本教程。

侧面导航链接无法正常工作,当我单击第二个菜单时,它将顺利显示 fragment2 但是当我单击第一个菜单以再次显示 fragment1 时,应用程序崩溃了..

这是我的代码..

MainActivity.java

package com.androidbegin.sidemenututorial;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;

public class MainActivity extends SherlockFragmentActivity {

// Declare Variable
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawer_main);

    // Generate title
    title = new String[] { "Promos", "Womens Wear",
    "Mens Wear" };

    // Generate subtitle
    subtitle = new String[] { "Subtitle Fragment 1", "Subtitle Fragment 2",
    "Subtitle Fragment 3" };

    // Generate icon
    icon = new int[] { R.drawable.menu_promo, R.drawable.menu_women,
            R.drawable.menu_men };

    // Locate DrawerLayout in drawer_main.xml
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Locate ListView in drawer_main.xml
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // Set a custom shadow that overlays the main content when the drawer
    // opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
            GravityCompat.START);

    // Pass results to MenuListAdapter Class
    mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);

    // Set the MenuListAdapter to the ListView
    mDrawerList.setAdapter(mMenuAdapter);

    // Capture button clicks on side menu
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

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

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        public void onDrawerClosed(View view) {
            // TODO Auto-generated method stub
            super.onDrawerClosed(view);
        }

        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub
            super.onDrawerOpened(drawerView);
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {

        if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            mDrawerLayout.openDrawer(mDrawerList);
        }
    }

    return super.onOptionsItemSelected(item);
}

// The click listener 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) {

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Locate Position
    switch (position) {
    case 0:
        ft.replace(R.id.content_frame, fragment1);
        break;
    case 1:
        ft.replace(R.id.content_frame, fragment2);
        break;
    case 2:
        ft.replace(R.id.content_frame, fragment3);
        break;
    }
    ft.commit();
    mDrawerList.setItemChecked(position, true);
    // Close drawer
    mDrawerLayout.closeDrawer(mDrawerList);
}

@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);
    // Pass any configuration change to the drawer toggles
    mDrawerToggle.onConfigurationChanged(newConfig);
}
}

片段1.java

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.actionbarsherlock.app.SherlockFragment;

public class Fragment1 extends SherlockFragment {

ImageView fashionImg;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment1, container, false);
    return rootView;

}

这是我的列表设计和适配器代码

WomenList.java

package com.androidbegin.sidemenututorial;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;

public class WomenList extends ListFragment {

// Array of strings storing country names
String[] brandname = new String[] {
        "Limited Collection",
        "Brand Collection",
        "LifeStyle Collection",
        "Famous Collection",
        "Lingerie"
};    

// Array of integers points to images stored in /res/drawable/
int[] imgbrands = new int[]{
        R.drawable.fashion,
        R.drawable.lingerie,
        R.drawable.fashion,
        R.drawable.samplemodel,
        R.drawable.lingerie

};


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {  

    // Each row in the list stores country name, currency and imgbrand
    List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();        

    for(int i=0;i<5;i++){
        HashMap<String, String> hm = new HashMap<String,String>();
        hm.put("txt", "Brand: " + brandname[i]);
        hm.put("imgbrand", Integer.toString(imgbrands[i]) );            
        aList.add(hm);        
    }

    // Keys used in Hashmap
    String[] from = { "txt","imgbrand" };

    // Ids of views in listview_layout
    int[] to = {R.id.txt,R.id.imgbrand};        

    // Instantiating an adapter to store each items
    // R.layout.listview_layout defines the layout of each item
    SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, 

R.layout.listview_layout, from, to);       

        setListAdapter(adapter);

        return super.onCreateView(inflater, container, savedInstanceState);     
    }

}

片段1.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment 
        android:id="@+id/brand_fragment"
        android:name="com.androidbegin.sidemenututorial.WomenList"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Listview_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="0dp"
    android:orientation="vertical"
    android:paddingBottom="5dp">

    <ImageView
        android:id="@+id/imgbrand"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:paddingBottom="1dp"
        android:scaleType="centerCrop" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#000000"
        android:paddingLeft="8dp" >

        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="24sp"
            android:textColor="#fefefe"
            android:fontFamily="sans-serif-light"
            android:padding="12dp" />
    </LinearLayout>

</LinearLayout>

日志猫:

08-22 19:33:18.990: D/AndroidRuntime(28096): Shutting down VM
08-22 19:33:18.990: W/dalvikvm(28096): threadid=1: thread exiting with uncaught exception (group=0x414592a0)
08-22 19:33:19.000: E/AndroidRuntime(28096): FATAL EXCEPTION: main
08-22 19:33:19.000: E/AndroidRuntime(28096): android.view.InflateException: Binary XML file line #7: Error inflating class fragment
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at com.androidbegin.sidemenututorial.Fragment1.onCreateView(Fragment1.java:20)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.os.Handler.handleCallback(Handler.java:615)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.os.Looper.loop(Looper.java:137)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.app.ActivityThread.main(ActivityThread.java:4898)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at java.lang.reflect.Method.invokeNative(Native Method)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at java.lang.reflect.Method.invoke(Method.java:511)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at dalvik.system.NativeStart.main(Native Method)
08-22 19:33:19.000: E/AndroidRuntime(28096): Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate id 0x7f04002d, tag null, or parent id 0x0 with another fragment for com.androidbegin.sidemenututorial.WomenList
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
08-22 19:33:19.000: E/AndroidRuntime(28096):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
08-22 19:33:19.000: E/AndroidRuntime(28096):    ... 19 more
4

1 回答 1

0
Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate id 0x7f04002d, tag null, or parent id 0x0 with another fragment for com.androidbegin.sidemenututorial.WomenList
    E/AndroidRuntime(28096):    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
    E/AndroidRuntime(28096):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)

注意: 当布局包含 . 仅当动态添加到片段时才支持嵌套片段。

嵌套片段

尝试以下修复它:

    public void onDestroyView() {
            super.onDestroyView(); 
            Fragment fragment = (getFragmentManager().findFragmentById(R.id.your_fragment));  
            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
            ft.remove(fragment);
            ft.commit();
//         ft.commitAllowingStateLoss(); //If u want to handle orientation as well
    }

然后您可以按如下方式创建视图:

private static View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        view = inflater.inflate(R.layout.main, container, false);
    } catch (InflateException e) {
        e.printStackTrace();
    }
    return view;
}

我还建议您在 MainActivity 中添加以下行,例如:

    ft.addToBackStack(null); 
//  ft.addToBackStack(Fragment.TAG); // to identify that fragment.
    ft.commit();
于 2013-08-22T12:16:50.373 回答