Fragment中监听onKey事件,没你想象的那么难。
项目中越来越多的用到Fragment,在用Fragment取代TabHost的时候遇到了一个问题,我们都知道,TabHost的Tab为Activity实例,有OnKey事件,但是Fragment中没有,但是又必须监听OnKey事件怎么办(不仅仅是退出哦),如果仅仅是退出我们可以在Activity中进行统一处理.
下面记录一下在ActionBar中监听Fragment的onKey事件。
ActionBar实现Onkey事件,判断当前的fragment是哪一个,是不是所需要的Fragment,然后在需要监听OnKey事件的Fragment中写一个静态方法,传递keycode与event事件即可。
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem; @SuppressLint("NewApi")
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener { private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private Fragment fg;
// Tab titles
private String[] tabs = { "TopRatedFragment", "GamesFragment", "MoviesFragment" }; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
} /**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
// actionBar.setSelectedNavigationItem(position);
actionBar.selectTab(actionBar.getTabAt(position));
mAdapter.getItem(position); } public void onPageScrolled(int arg0, float arg1, int arg2) {
} public void onPageScrollStateChanged(int arg0) {
}
});
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
//
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
getMenuInflater().inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_settings);
SearchView searchview = (SearchView)MenuItemCompat.getActionView(searchItem);
searchview.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
} public void onTabReselected(Tab arg0,
android.support.v4.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub } public void onTabSelected(Tab arg0,
android.support.v4.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub
viewPager.setCurrentItem(arg0.getPosition());
fg = mAdapter.getItem(arg0.getPosition());
Log.d("fg", fg+"");
} public void onTabUnselected(Tab arg0,
android.support.v4.app.FragmentTransaction arg1) {
// TODO Auto-generated method stub } @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
Log.d("ActionBar", "OnKey事件");
if(fg instanceof GamesFragment){
GamesFragment.onKeyDown(keyCode, event);
}
return super.onKeyDown(keyCode, event);
}
}
其中一个Fragment
package info.androidhive.tabsswipe; import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast; public class GamesFragment extends Fragment { private View view; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_games, container, false);
}
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
return view;
} @Override
public void onResume() {
super.onResume();
// 判断当前fragment是否显示
if (getUserVisibleHint()) {
showdata();
}
} @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// 每次切换fragment时调用的方法
if (isVisibleToUser) {
showdata();
}
} private void showdata() {
Toast.makeText(getActivity(), "Game", Toast.LENGTH_LONG).show();
} public static boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_BACK) {
Log.d("GameFragmet事件", "OK");
}
return true;
}
}
最后当我在Fragment中触发Onkey事件后打印日志

另外一种解决方法:

Fragment中监听onKey事件,没你想象的那么难。的更多相关文章
- wemall app商城源码Fragment中监听onKey事件
wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享android开发Fragment中监听onK ...
- 在Javascript中监听flash事件(转)
在Javascript中监听flash事件,其实有两种做法: 1.在特定的环境下(例如专门制作的flash),大家约定一个全局函数,然后在flash的事件中用ExternalInterface.cal ...
- 【Layui__监听button】在form中监听按钮事件
1. 前言 在使用form表单的按钮时,点击按钮总是页面刷新,代码如下 <button class="layui-btn" lay-submit lay-filter=&qu ...
- Fragment中 监听Android 返回按钮事件
@Override public void onResume() { super.onResume(); getView().setFocusableInTouchMode(true); getVie ...
- Vue中监听 键盘事件及修饰符
键盘事件: keyCode 实际值 48到57 0 - 9 65到90 a - z ( A-Z ) 112到135 F1 - F24 8 ...
- android fragment轻松监听返回键/Fragment中的popupwindow响应返回键隐藏
现在的开发我们基本上都是一个主activity中放多个fragment,点击返回按钮的时候,直接退出主activity,但是我们在fragment中经常会弹出例如popupWindow这样的布局,用户 ...
- Vue 爬坑之路(七)—— 监听滚动事件 实现动态锚点
前几天做项目的时候,需要实现一个动态锚点的效果 如果是传统项目,这个效果就非常简单.但是放到 Vue 中,就有两大难题: 1. 在没有 jQuery 的 animate() 方法的情况下,如何实现平滑 ...
- vue监听滚动事件
vue中监听滚动事件,然后对其进行事件处理,一般有:1. 滚动到顶部吸附: 2. 根据滚动的位置激活对应的tab键(锚链接tab键) 这两种方式的处理都是可通过监听scroll来实现 mounted( ...
- 在Activity,Service,Window中监听Home键和返回键的一些思考,如何把事件传递出来的做法!
在Activity,Service,Window中监听Home键和返回键的一些思考,如何把事件传递出来的做法! 其实像按键的监听,我相信很多人都很熟练了,我肯定也不会说这些基础的东西,所以,前期,还是 ...
随机推荐
- iOS开发笔记10:圆点缩放动画、强制更新、远程推送加语音提醒及UIView截屏
1.使用CAReplicatorLayer制作等待动画 CALayer+CABasicAnimation可以制作很多简单的动画效果,之前的博客中介绍的“两个动画”,一个是利用一张渐变色图片+CABas ...
- HTML5 拖放
拖放(Drag 和 drop)是 HTML5 标准的组成部分. 拖放 拖放是一种常见的特性,即抓取对象以后拖到另一个位置. 在 HTML5 中,拖放是标准的一部分,任何元素都能够拖放. 浏览器支持 I ...
- 博客建议(Suggestions)
I don't know if you will like the music. But I am sure there are some songs which are really wonderf ...
- fragment 切换
1.Fragment的添加方式 FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.hide ft.show ft ...
- [PL/SQL工具]绿色版PLSQL工具登录时提示初始化失败,无法锁定OCI.dll错误
问题现象:使用绿色版PL/SQL工具进行登录时报如下截图错误: 问题描述:初始化失败,无法锁定oci.dll 解决方法:在PLSQL的菜单栏里依次选择 工具->首选项,在OCI库(自动检测为空) ...
- WebService核心之WSDL深入详解
WebService核心之WSDL深入详解 根据上一篇文章开发的Web Service实例生成的WSDL文档如下: XML里两个属性介绍: targetNamespace 相当于ja ...
- CentOS下安装MySQL
首先通过网络链接的方式在线安装上mysql服务器端吧!(备注:我开始登录服务器的时候是用的其他用户而不是超级管理员,所以安装MySQL的时候需要切换到超级管理员才可以实现软件的正确安装.命令则是:su ...
- Linux 下编译安装软件,找不到共享库 xx.so 的解决办法
编译memcached时,报错没有libevent,于是下载libevent,configure , make && make install ,然后在重新安装memcache成功之后 ...
- 第二章 Mysql 数据类型简介--(整数类型、浮点数类型和定点数类型,日期与时间类型,字符串类型,二进制类型)
第一节:整数类型.浮点数类型和定点数类型 1,整数类型 2,浮点数类型和定点数类型 M 表示:数据的总长度(不包括小数点):D 表示:小数位:例如 decimal(5,2) 123.45存入数据的时候 ...
- hdu 4738 Caocao's Bridges 图--桥的判断模板
Caocao's Bridges Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...