在Navigation-Drawer的抽屉中加载自定义片段,并在主布局中打开相应的片段

时间:2013-11-28 16:05:23

标签: android android-fragments navigation-drawer

我想根据某些条件在抽屉中装入不同的碎片。说:

if(bit =0){
load fragment0();
}
else if(bit =1){
load fragment1();
}

每个片段(fragment0& fragment1)都包含自己的项目列表和按钮/视图。 然后根据项目点击抽屉片段,我想在主布局中加载相应的片段。 以下是我正在使用的代码:

这是在抽屉中加载不同片段的主要活动

public class LaunchActivity extends FragmentActivity {

private DrawerLayout DrawerLayout;
//private ListView DrawerList;
private FrameLayout DrawerList;
private ActionBarDrawerToggle DrawerToggle;

@SuppressWarnings("unused")
private CharSequence DrawerTitle;
private CharSequence Title;
private String[] ListTitles;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawerlist_test);

    Title = DrawerTitle = getTitle();
    ListTitles = getResources().getStringArray(R.array.list_array);
    DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    //DrawerList = (ListView) findViewById(R.id.left_drawer);
    DrawerList = (FrameLayout) findViewById(R.id.left_drawer);


    // initialize drawer list 
    // Also set a custom shadow that overlays the main content when the drawer opens
    DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

// change frames
    int bit =0;

    if(bit==1){     
    // add fragments to drawer list
    Fragment newFragment;
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    newFragment = new testfragment();
    transaction.add(R.id.left_drawer, newFragment);
    transaction.addToBackStack(null);
    transaction.commit(); 

    }

    else 
    {
        // add fragments to drawer list
        Fragment newFragment;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        newFragment = new testfragment1();
        transaction.add(R.id.left_drawer, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }




    // set up the drawer's list view with items and click listener
//  DrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_itemlist, ListTitles));
//  DrawerList.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
    DrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            DrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_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(Title);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(Title); // same title for open/close drawer
            //getActionBar().setTitle(DrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    DrawerLayout.setDrawerListener(DrawerToggle);
    if (savedInstanceState == null) {
//      selectItem(0);
    }
}


/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 */



@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    DrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggle
    DrawerToggle.onConfigurationChanged(newConfig);
}   





// option menu - action bar   
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}


// 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
    boolean drawerOpen = DrawerLayout.isDrawerOpen(DrawerList);
    menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
    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 (DrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }


    // Handle action buttons
    switch(item.getItemId()) {
    case R.id.action_websearch:
        // create intent to perform web search for this planet
        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
        // catch event that there's no activity to handle intent
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}



/*
// Nav Drawer List click
// The click listener for ListView in the navigation drawer
@SuppressWarnings("unused")
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) {

    Fragment newFragment;
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    switch (position) {
    case 0:
        newFragment = new f1();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;

    case 1:
        newFragment = new f2();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;

    case 2:
        newFragment = new f3();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;

    case 3:
        newFragment = new f4();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        break;  


    }
    //DrawerList.setItemChecked(position, true);
    setTitle(ListTitles[position]);
    DrawerLayout.closeDrawer(DrawerList);   
}


@Override
public void setTitle(CharSequence title) {
    Title = title;
    getActionBar().setTitle(Title);
}
*/
}

fragment1的源代码:

public class testfragment extends Fragment {

ListView DrawerList;
private String[] ListTitles;

 private List<String> mDataSourceList = new ArrayList<String>();  
 private List<FragmentTransaction> mBackStackList = new ArrayList<FragmentTransaction>();  

    public static Fragment newInstance(Context context) {
    testfragment f = new testfragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.activity_testfragment, null);

    return root;
}


@Override 
public void onActivityCreated(Bundle savedInstanceState) {  
    super.onActivityCreated(savedInstanceState);  

    //add data to ListView  
    for(int i=0, count=20; i<count; i++){  
        mDataSourceList.add("record" + i);  
    } 

    ListView listView = (ListView) getActivity().findViewById(R.id.listView1);  
    listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, mDataSourceList));  

}   

public android.app.Fragment commit() {
    // TODO Auto-generated method stub
    return null;
}

}

片段2也有类似的代码,但列表中有不同的项目。 取决于比特值,两个片段在抽屉中完全加载。现在当有人点击抽屉列表项时,我想在主布局中加载相应的片段。

我的问题是Where&amp;我应该如何为listview添加onclicklistener,以便在抽屉关闭后在主要内容中生成适当的片段?在相应的fragment1 / 2或主要活动中。

我还有另一种方法可以在man活动中使用不同的列表来做同样的事情。 我能做的是 - 在主要活动中声明两个不同的列表视图及其onclicklistener开关案例。然后我可以在抽屉中使用if-else条件加载那些列表视图。

对于灵活,结构良好且设计良好的应用程序而言,有什么可能是更好的方法。

以下是我的问题的另一部分:Load navigation drawer slider with Dynamic Fragments

1 个答案:

答案 0 :(得分:1)

您应该为片段创建接口,然后使用回调方法来警告活动。这是一个示例代码。

 public class FirstDrawerFragment extends Fragment {

    FirstDrawerListener mListener;

    public interface FirstDrawerListener{
        public void onSomeThingHappend(Data youWantToPass);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mListener = (FirstDrawerListener)activity;

    }

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

        v.findViewById(R.id.someview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onSomeThingHappend(data);
            }
        });
        return super.onCreateView(inflater, container, savedInstanceState);
    }
}

public class SecondDrawerFragment extends Fragment {

    SecondDrawerListener mListener;

    public interface SecondDrawerListener{
        public void onSomeThingHappendSecond(Data youWantToPass);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        mListener = (SecondDrawerListener)activity;

    }

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

        v.findViewById(R.id.someview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onSomeThingHappend(data);
            }
        });
        return super.onCreateView(inflater, container, savedInstanceState);
    }
}


public class YourActivity extends Activity FirstDrawerListener ,SecondDrawerListner{

    @Override
    public void onSomeThingHappend(Data youWantToPass){

        //do your thing and add some fragments
        //close drawer
    }

    @Override
    public void onSomeThingHappendSecond(Data youWantToPass){

        //do yout thing and add some fragments
        //close drawer
    }

}

希望它适合你!