问题描述
我有我的抽屉式导航活性我MainActivity类别和我已经有Homepage.class活动previously的。由于导航抽屉使用的片段,我无法通过抽屉调用HomePage类。 PLZ帮我。
下面是我的code的抽屉 -
公共类MainActivity延伸活动{
私人DrawerLayout mDrawerLayout;
私人的ListView mDrawerList;
私人ActionBarDrawerToggle mDrawerToggle;//导航抽屉称号
私人CharSequence的mDrawerTitle;//用于存储应用程序标题
私人CharSequence的mTitle;//滑动菜单项
私有String [] navMenuTitles;
私人TypedArray navMenuIcons;私人的ArrayList< NavDrawerItem> navDrawerItems;
私人NavDrawerListAdapter适配器;@燮pressLint(NewApi)
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main); mTitle = mDrawerTitle =的getTitle(); //负荷滑动菜单项
navMenuTitles = getResources()getStringArray(R.array.nav_drawer_items)。 从资源//导航抽屉图标
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons); mDrawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList =(ListView控件)findViewById(R.id.list_slidermenu); navDrawerItems =新的ArrayList< NavDrawerItem>(); //添加导航抽屉里的物品数组
//首页
navDrawerItems.add(新NavDrawerItem(navMenuTitles [0],navMenuIcons.getResourceId(0,-1)));
//找人
navDrawerItems.add(新NavDrawerItem(navMenuTitles [1],navMenuIcons.getResourceId(1,-1)));
// 相片
navDrawerItems.add(新NavDrawerItem(navMenuTitles [2],navMenuIcons.getResourceId(2,-1)));
//社区,这里将添加计数器
navDrawerItems.add(新NavDrawerItem(navMenuTitles [3],navMenuIcons.getResourceId(3,-1),真的,22));
//网页
navDrawerItems.add(新NavDrawerItem(navMenuTitles [4],navMenuIcons.getResourceId(4,-1)));
//什么是热的,我们将在这里添加计数器
navDrawerItems.add(新NavDrawerItem(navMenuTitles [5],navMenuIcons.getResourceId(5,-1),真的,50+));
//回收类型数组
navMenuIcons.recycle(); mDrawerList.setOnItemClickListener(新SlideMenuClickListener()); //设置导航抽屉名单适配器
适配器=新NavDrawerListAdapter(getApplicationContext()
navDrawerItems);
mDrawerList.setAdapter(适配器); //使操作栏中的应用程序图标和行为作为切换按钮
getActionBar()setDisplayHomeAsUpEnabled(真)。
getActionBar()setHomeButtonEnabled(真)。 mDrawerToggle =新ActionBarDrawerToggle(这一点,mDrawerLayout,
R.drawable.ic_drawer,//导航菜单切换图标
R.string.app_name,//导航抽屉打开 - 描述的可访问性
R.string.app_name //导航抽屉接近 - 描述的可访问性
){
公共无效onDrawerClosed(查看视图){
。getActionBar()的setTitle(mTitle);
//调用prepareOptionsMenu()来显示操作栏图标
invalidateOptionsMenu();
} 公共无效onDrawerOpened(查看drawerView){
。getActionBar()的setTitle(mDrawerTitle);
//调用prepareOptionsMenu()隐藏操作栏图标
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle); 如果(savedInstanceState == NULL){
//对第一个项目的资产净值首次显示视图
displayView(0);
}
}/ **
*滑动菜单项,点击监听器
* * /
私有类SlideMenuClickListener工具
ListView.OnItemClickListener {
@覆盖
公共无效onItemClick(适配器视图<>母公司,观景,INT位置,
长ID){
//选定导航抽屉项显示视图
displayView(位置);
}
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
//切换上选择操作栏中的应用程序图标/标题导航抽屉
如果(mDrawerToggle.onOptionsItemSelected(项目)){
返回true;
}
//处理操作栏中点击动作
开关(item.getItemId()){
案例R.id.action_settings:
返回true;
默认:
返回super.onOptionsItemSelected(项目);
}
}/ * *
*时调用invalidateOptionsMenu()被触发
* /
@覆盖
prepareOptionsMenu(菜单菜单)上公共布尔{
//如果导航抽屉被打开,隐藏行动项目
布尔drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(drawerOpen!);
返回super.on prepareOptionsMenu(菜单);
}/ **
所选导航抽屉列表项* Diplaying片段视图
* * /
私人无效displayView(INT位置){
//更新替换片段的主要内容
片段片段= NULL;
开关(位置){
情况下0:
片段=新HomeFragment();
打破;
情况1:
片段=新FindPeopleFragment();
打破;
案例2:
片段=新PhotosFragment();
打破;
案例3:
片段=新CommunityFragment();
打破;
情况4:
片段=新PagesFragment();
打破;
情况5:
片段=新WhatsHotFragment();
打破; 默认:
打破;
} 如果(片段!= NULL){
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container,片段).commit(); //更新所选项目和标题,然后关上抽屉
mDrawerList.setItemChecked(位置,真正的);
mDrawerList.setSelection(位置);
(navMenuTitles [位置])的setTitle;
mDrawerLayout.closeDrawer(mDrawerList);
}其他{
//错误创建片段
Log.e(MainActivity,出错创建片段);
}
}@覆盖
公共无效的setTitle(CharSequence的标题){
mTitle =称号;
。getActionBar()的setTitle(mTitle);
}/ **
*当使用ActionBarDrawerToggle,你必须在调用它
* onPostCreate()和onConfigurationChanged()...
* /@覆盖
保护无效onPostCreate(捆绑savedInstanceState){
super.onPostCreate(savedInstanceState);
//同步onRestoreInstanceState后切换状态已经发生。
mDrawerToggle.syncState();
}@覆盖
公共无效onConfigurationChanged(配置NEWCONFIG){
super.onConfigurationChanged(NEWCONFIG);
//把任何配置更改抽屉toggls
mDrawerToggle.onConfigurationChanged(NEWCONFIG);
}
}
我的一个片段 -
公共类HomeFragment扩展片段{公共HomeFragment(){}@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
捆绑savedInstanceState){ 意向意图=新的Intent();
intent.setClass(getActivity(),HomePage.class);
startActivity(意向);
查看rootView = inflater.inflate(R.layout.activity_main,集装箱,FALSE); 返回rootView;
}
首页活动,我要的是点击导航抽屉项时调用:
公共类首页扩展MainActivity {
私有静态最后弦乐TAG = MainActivity.class.getSimpleName();
私人的ListView ListView的;
私人FeedListAdapter listAdapter;
私人列表< FeedItem> feedItems;
私人字符串URL_FEED = \"https://gist.githubusercontent.com/anonymous/e6c3336c57bf40c794ab/raw/022058ac0ceafd15bfed89a72e6b741dd84da130/blob.json\";
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.fragment_home); ListView控件=(ListView控件)findViewById(R.id.list); feedItems =新的ArrayList< FeedItem>(); listAdapter =新FeedListAdapter(这一点,feedItems);
listView.setAdapter(listAdapter); //并不需要这两行,
//只是为了让Facebook的外观(改变背景颜色和放大器;隐藏的图标)
getActionBar()setBackgroundDrawable(新ColorDrawable(Color.parseColor(#EF7B00)))。
// getActionBar()的setIcon(
//新ColorDrawable(getResources()的getColor(android.R.color.transparent))); //我们首先检查缓存请求
缓存缓存= AppController.getInstance()getRequestQueue()getCache()。
中入口= cache.get(URL_FEED);
如果(入门!= NULL){
//获取从缓存中的数据
尝试{
字符串数据=新的String(entry.data,UTF-8);
尝试{
parseJsonFeed(新的JSONObject(数据));
}赶上(JSONException E){
e.printStackTrace();
}
}赶上(UnsupportedEncodingException五){
e.printStackTrace();
} }其他{
//使新鲜的凌空请求,并得到JSON
JsonObjectRequest jsonReq =新JsonObjectRequest(Method.GET,
URL_FEED,空,新Response.Listener<&JSONObject的GT;(){ @覆盖
公共无效onResponse(JSONObject的响应){
VolleyLog.d(TAG,回应:+ response.toString());
如果(响应!= NULL){
parseJsonFeed(响应);
}
}
},新Response.ErrorListener(){ @覆盖
公共无效onErrorResponse(VolleyError错误){
VolleyLog.d(TAG,错误:+ error.getMessage());
}
}); //添加请求凌空请求队列
。AppController.getInstance()addToRequestQueue(jsonReq);
}}/ **
*解析JSON作出反应并传递数据养活查看列表适配器
* * /
私人无效parseJsonFeed(JSONObject的响应){
尝试{
JSONArray feedArray = response.getJSONArray(饲料); 的for(int i = 0; I< feedArray.length();我++){
JSONObject的feedObj =(JSONObject的)feedArray.get(I) FeedItem项目=新FeedItem();
item.setId(feedObj.getInt(ID));
item.setName(feedObj.getString(名字)); //图片可能为空有时
字符串图像= feedObj.isNull(图像)?空:feedObj
.getString(图像);
item.setImge(图片);
item.setStatus(feedObj.getString(身份));
item.setProfilePic(feedObj.getString(profilePic));
item.setTimeStamp(feedObj.getString(时间戳)); // URL可能为空有时
字符串feedUrl = feedObj.isNull(URL)?空:feedObj
.getString(URL);
item.setUrl(feedUrl); feedItems.add(项目);
} //通知数据的变化,列出adapater
listAdapter.notifyDataSetChanged();
}赶上(JSONException E){
e.printStackTrace();
}
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
} }
XML的抽屉:
< android.support.v4.widget.DrawerLayout
的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:ID =@ + ID / drawer_layout
机器人:layout_width =match_parent
机器人:layout_height =match_parent> <! - 的FrameLayout显示片段 - > <的FrameLayout
机器人:ID =@ + ID / frame_container
机器人:layout_width =match_parent
机器人:layout_height =match_parent> < /&的FrameLayout GT; <! - 列表视图显示滑块菜单 - > < ListView控件
机器人:ID =@ + ID / list_slidermenu
机器人:layout_width =240dp
机器人:layout_height =match_parent
机器人:layout_gravity =开始
机器人:背景=@彩色/ list_background
机器人:choiceMode =singleChoice
机器人:分=@彩色/ list_divider
机器人:dividerHeight =1DP
机器人:listSelector =@绘制/ list_selector/>
< /android.support.v4.widget.DrawerLayout>
和最后的XML,我想被称为活动 -
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent>< ListView控件
机器人:ID =@ + ID /列表
机器人:layout_width =FILL_PARENT
机器人:layout_height =WRAP_CONTENT
机器人:分=@空/> < / LinearLayout中>
启动一个活动使用导航纸盒时,不会改变的API。你仍然只需要调用 startActivity()
来推出不同的活动。
在这种情况下,您的code会是这个样子:
私人无效displayView(INT位置){
//更新替换片段的主要内容
片段片段= NULL;
开关(位置){
案件0://或任何导航项目位置应该启动活动
startActivity(新意图(这一点,HomePage.class));
返回; //你的情况下,其余
}
请注意,当调用后 startActivity()
的主页项目,我们,而不是返回
破
让你的 displayView()
不尝试更换显示的片段。
I have my navigation drawer activity as my MainActivity class and I already have Homepage.class activity previously made. Since Navigation Drawer uses Fragments, I am unable to call Homepage class through Drawer. Plz help me.
Here is my code for the Drawer-
public class MainActivity extends Activity {
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;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
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.frame_container, 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);
}
}
One of my fragments -
public class HomeFragment extends Fragment {
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = new Intent();
intent.setClass(getActivity(), HomePage.class);
startActivity(intent);
View rootView = inflater.inflate(R.layout.activity_main, container, false);
return rootView;
}
HomePage Activity which I want to call when item on navigation drawer is clicked :
public class HomePage extends MainActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "https://gist.githubusercontent.com/anonymous/e6c3336c57bf40c794ab/raw/022058ac0ceafd15bfed89a72e6b741dd84da130/blob.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#EF7B00")));
// getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
XML for the drawer:
<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 to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!-- 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:background="@color/list_background"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector" />
</android.support.v4.widget.DrawerLayout>
And Finally XML for the activity which I want to be called -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="@null" />
</LinearLayout>
The API for starting an Activity does not change when using a navigation drawer. You still only need to call startActivity()
to launch a different Activity.
In this case, your code will look something like this:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0: // Or whatever nav item position should start the Activity
startActivity(new Intent(this, HomePage.class));
return;
// The rest of your cases
}
Note that when after calling startActivity()
for the homepage item, we return
instead of break
so that your displayView()
doesn't try to replace the displayed Fragment.
这篇关于我怎么能叫用抽屉式导航我的活动之一吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!