Android 如何使用碎片主细节实现导航抽屉
我已从该网站获得导航抽屉示例: 这里的主要细节是: 错误LogCat oncreateview(inflac…)显示在视图中 无法创建 告诉我我试过了Android 如何使用碎片主细节实现导航抽屉,android,android-fragments,navigation-drawer,master-detail,Android,Android Fragments,Navigation Drawer,Master Detail,我已从该网站获得导航抽屉示例: 这里的主要细节是: 错误LogCat oncreateview(inflac…)显示在视图中 无法创建 告诉我我试过了 //the main activiry as Activity: package in.wptrafficanalyzer.listfragmentitemclick; import in.wptrafficanalyzer.listfragmentitemclick.adapter.NavDrawerListAdapte
//the main activiry as Activity:
package in.wptrafficanalyzer.listfragmentitemclick;
import in.wptrafficanalyzer.listfragmentitemclick.adapter.NavDrawerListAdapter;
import in.wptrafficanalyzer.listfragmentitemclick.model.NavDrawerItem;
import java.util.ArrayList;
import in.wptrafficanalyzer.listfragmentitemclick.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity implements CountryListFragment.ListFragmentItemClickListener {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
ListFragment fragment = null;
switch (position) {
case 0:
//fragment = new HomeFragment();
break;
case 1:
fragment = new CountryListFragment();
break;
case 2:
//fragment = new PhotosFragment();
break;
case 3:
// fragment = new CommunityFragment();
break;
case 4:
//fragment = new PagesFragment();
break;
case 5:
//fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.country_list_fragment, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* 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.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/** Called when the activity is first created. */
@Override
public void onListFragmentItemClick(int position) {
/** Getting the orientation ( Landscape or Portrait ) of the screen */
int orientation = getResources().getConfiguration().orientation;
/** Landscape Mode */
if(orientation == Configuration.ORIENTATION_LANDSCAPE ){
/** Getting the fragment manager for fragment related operations */
FragmentManager fragmentManager = getFragmentManager();
/** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
/** Getting the existing detailed fragment object, if it already exists.
* The fragment object is retrieved by its tag name
* */
Fragment prevFrag = fragmentManager.findFragmentByTag("in.wptrafficanalyzer.country.details");
/** Remove the existing detailed fragment object if it exists */
if(prevFrag!=null)
fragmentTransaction.remove(prevFrag);
/** Instantiating the fragment CountryDetailsFragment */
CountryDetailsFragment fragment = new CountryDetailsFragment();
/** Creating a bundle object to pass the data(the clicked item's position) from the activity to the fragment */
Bundle b = new Bundle();
/** Setting the data to the bundle object */
b.putInt("position", position);
/** Setting the bundle object to the fragment */
fragment.setArguments(b);
/** Adding the fragment to the fragment transaction */
fragmentTransaction.add(R.id.detail_fragment_container, fragment,"in.wptrafficanalyzer.country.details");
/** Adding this transaction to backstack */
fragmentTransaction.addToBackStack(null);
/** Making this transaction in effect */
fragmentTransaction.commit();
}else{ /** Portrait Mode or Square mode */
/** Creating an intent object to start the CountryDetailsActivity */
Intent intent = new Intent("in.wptrafficanalyzer.CountryDetailsActivity");
/** Setting data ( the clicked item's position ) to this intent */
intent.putExtra("position", position);
/** Starting the activity by passing the implicit intent */
startActivity(intent);
}
}
}
//作为活动的主活动:
package in.wptrafficanalyzer.listfragmentitemclick;
导入in.wptrafficanalyzer.listfragmentitemclick.adapter.NavDrawerListAdapter;
导入in.wptrafficanalyzer.listfragmentitemclick.model.NavDrawerItem;
导入java.util.ArrayList;
导入.wptrafficanalyzer.listfragmentitemclick.R;
导入android.app.Activity;
导入android.app.Fragment;
导入android.app.FragmentManager;
导入android.app.FragmentTransaction;
导入android.app.ListFragment;
导入android.content.Intent;
导入android.content.res.Configuration;
导入android.content.res.TypedArray;
导入android.os.Bundle;
导入android.support.v4.app.ActionBarDrawerToggle;
导入android.support.v4.widget.DrawerLayout;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.ListView;
公共类MainActivity扩展活动实现CountryListFragment.ListFragmentItemClickListener{
私人抽屉布局mDrawerLayout;
私有列表视图mDrawerList;
私有操作bardrawertoggle mDrawerToggle;
//导航抽屉标题
私有字符序列mDrawerTitle;
//用于存储应用程序标题
私有字符序列mTitle;
//幻灯片菜单项
私有字符串[]navMenuTitles;
专用型雷达导航仪;
私人ArrayList NavWrites;
专用导航适配器;
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTitle=mDrawerTitle=getTitle();
//加载幻灯片菜单项
navMenuTitles=getResources().getStringArray(R.array.nav\u抽屉\u项目);
//参考资料中的导航抽屉图标
navMenuIcons=getResources()
.obtainTypedArray(R.array.nav_drawer_图标);
mDrawerLayout=(抽屉布局)findViewById(R.id.抽屉布局);
mDrawerList=(ListView)findViewById(R.id.list\u slidermenu);
navDrawerItems=新的ArrayList();
//将导航抽屉项添加到阵列
//家
添加(新的NavDrawerItem(navMenuTitles[0],navMenuIcons.getResourceId(0,-1));
//找人
添加(新的NavDrawerItem(navMenuTitles[1],navMenuIcons.getResourceId(1,-1));
//照片
添加(新的NavDrawerItem(navMenuTitles[2],navMenuIcons.getResourceId(2,-1));
//社区,将在此处添加一个计数器
添加(新的NavDrawerItem(navMenuTitles[3],navMenuIcons.getResourceId(3,-1),true,“22”);
//页数
add(新的NavDrawerItem(navMenuTitles[4],navMenuIcons.getResourceId(4,-1));
//什么是热的,我们将在这里加一个计数器
add(新的NavDrawerItem(navMenuTitles[5],navMenuIcons.getResourceId(5,-1),true,“50+”));
//回收类型化数组
navMenuIcons.recycle();
setOnItemClickListener(新的SlideMenuClickListener());
//设置导航抽屉列表适配器
适配器=新的NavDroperListAdapter(getApplicationContext(),
纳维特姆斯);
mDrawerList.setAdapter(适配器);
//启用操作栏应用程序图标并将其作为切换按钮
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle=新操作BarDrawerToggle(此,mDrawerLayout,
R.drawable.ic_抽屉,//导航菜单切换图标
R.string.app_name,//导航抽屉打开-可访问性说明
R.string.app_name//nav抽屉关闭-可访问性说明
) {
公共无效onDrawerClosed(视图){
getActionBar().setTitle(mTitle);
//调用onPrepareOptions菜单()以显示操作栏图标
无效操作菜单();
}
打开图纸上的公共空白(视图抽屉视图){
getActionBar().setTitle(mDrawerTitle);
//调用onPrepareOptions菜单()隐藏操作栏图标
无效操作菜单();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
如果(savedInstanceState==null){
//第一个导航项目的首次显示视图
显示视图(0);
}
}
/**
*幻灯片菜单项单击“侦听器”
* */
私有类SlideMenuClickListener实现
ListView.com侦听器{
@凌驾
public void onItemClick(AdapterView父视图、视图、整型位置、,
长id){
//所选导航抽屉项目的显示视图
显示视图(位置);
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(R.menu.main,menu);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//在选择操作栏应用程序图标/标题时切换导航抽屉
如果(MDRAWERTOGLE.onOptionsItemSelected(项目)){
返回true;
}
//处理操作栏操作单击
开关(item.getItemId()){
案例R.id.action\u设置:
返回true;
违约:
返回super.onOptionsItemSelected(项目);
}
}
/***
*在触发InvalidateOptions菜单()时调用
*/
@凌驾
公共布尔值OnPrepareOptions菜单(菜单){
//如果导航抽屉打开,则隐藏操作项
boolean-DrawerLayout=mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action\u设置).setV
package in.wptrafficanalyzer.listfragmentitemclick;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class CountryListFragment extends ListFragment{
/** List of countries to be displayed in the ListFragment */
ListFragmentItemClickListener ifaceItemClickListener;
/** An interface for defining the callback method */
public interface ListFragmentItemClickListener {
/** This method will be invoked when an item in the ListFragment is clicked */
void onListFragmentItemClick(int position);
}
/** A callback function, executed when this fragment is attached to an activity */
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
/** This statement ensures that the hosting activity implements ListFragmentItemClickListener */
ifaceItemClickListener = (ListFragmentItemClickListener) activity;
}catch(Exception e){
Toast.makeText(activity.getBaseContext(), "Exception",Toast.LENGTH_SHORT).show();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/** Data source for the ListFragment */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1, Country.name);
/** Setting the data source to the ListFragment */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
/** Invokes the implementation of the method istFragmentItemClick in the hosting activity */
ifaceItemClickListener.onListFragmentItemClick(position);
}
}
><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/country_list_fragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:name="in.wptrafficanalyzer.listfragmentitemclick.CountryListFragment"
/>
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
> </android.support.v4.widget.DrawerLayout>
><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/country_list_fragment"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:name="in.wptrafficanalyzer.listfragmentitemclick.CountryListFragment"
/>
<FrameLayout
android:id="@+id/detail_fragment_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
/>
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
></android.support.v4.widget.DrawerLayout>
public class MainActivity extends Activity
implements OnItemClickListener, ItemListFragment.Callbacks {
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-large and
// res/values-sw600dp). If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
// In two-pane mode, list items should be given the
// 'activated' state when touched.
((ItemListFragment) getFragmentManager()
.findFragmentById(R.id.item_list))
.setActivateOnItemClick(true);
}
if (mTwoPane) {
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
// In single-pane mode, simply start the detail activity
// for the selected item ID.
Intent detailIntent = new Intent(this, ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}