android - Unable to use OptionsMenu in Fragment Activity -
i want use options menu inside fragment activity
.i have used following code add option menu
:
1.menu_chat.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_viewcontacts" android:orderincategory="100" android:title="@string/action_view_contacts" app:showasaction="never"/> <item android:id="@+id/action_media" android:orderincategory="100" android:title="@string/action_media" app:showasaction ="never"/> <item android:id="@+id/action_search_message" android:orderincategory="100" android:title="@string/action_search" app:showasaction ="never"/> <item android:id="@+id/action_block" android:orderincategory="100" android:title="@string/action_block" app:showasaction ="never"/> <item android:id="@+id/action_email_chat" android:orderincategory="100" android:title="@string/action_email_chat" app:showasaction ="never"/> <item android:id="@+id/action_clear_chat" android:orderincategory="100" android:title="@string/action_clear_chat" app:showasaction ="never"/> <item android:id="@+id/action_attach" android:orderincategory="100" android:title="@string/action_clear_chat" android:icon="@drawable/attach" app:showasaction ="always"/> </menu>
2.code of fragmentactivity
@override public boolean oncreateoptionsmenu(menu menu) { log.e("option menu","called"); menuinflater inflater = getmenuinflater(); inflater.inflate(r.menu.menu_chat_activity, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case r.id.action_viewcontacts: return true; case r.id.action_media: return true; case r.id.action_search: return true; case r.id.action_block: return true; case r.id.action_email_chat: return true; case r.id.action_clear_chat: return true; case r.id.action_attach: return true; default: return super.onoptionsitemselected(item); } }
when run code,options menu
never displayed.
i have checked inside log
oncreateoptionsmenu
not called .in 1 of screen have used appcompatactivity
.for options menu working .i have to use fragmentactivity
here .please me fix issue.
complete code of fragmentactivity:
public class singlechatactivity extends fragmentactivity implements emojicongridfragment.onemojiconclickedlistener, emojiconsfragment.onemojiconbackspaceclickedlistener { private string url_feed_message, api_message; private string frndid, id; private sharedpreferences sharedpreferences; private int loggedinuserid, friendid, smallerid, largerid; private string sid, lid, md5stringroomid; private apiconfiguration apiconfiguration; private httprequestprocessor httprequestprocessor; private networkconnectiondetector networkconnectiondetector; private bean_message msg; private boolean isself; private list<bean_message> listbeanmessages; private adapter_message adapter_message; private listview lv_message; private string friendname, completeurlfriend; private emojiconedittext edmessage; private socket msocket; private boolean showemoji = false; private boolean hideemoji; int deviceheight; framelayout framelayout; private string message; private string loggedinupper, loggedinuser; // instance initialization block { try { msocket = io.socket(constants.chat_server_url); log.e("socket", string.valueof(msocket)); } catch (urisyntaxexception e) { throw new runtimeexception(e); } } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_single_chat); //toolbar toolbar toolbar = (toolbar) findviewbyid(r.id.toolbarsinglechat); toolbar.setnavigationicon(r.drawable.back); // setting navigation icon in toolbar //findviewbyid lv_message = (listview) findviewbyid(r.id.lv_message); edmessage = (emojiconedittext) findviewbyid(r.id.edtmessage); //handling click event on navigation icon toolbar.setnavigationonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { startactivity(new intent(singlechatactivity.this, friendslistactivity.class)); } }); //getting values previos screen(chatfragment) bundle bundle = getintent().getextras(); friendname = bundle.getstring("friendsname", null); completeurlfriend = bundle.getstring("absoluteurl", null); frndid = bundle.getstring("friendid"); //initialization sharedpreferences = getapplicationcontext().getsharedpreferences(prefs_registration.prefsname, context.mode_private); apiconfiguration = new apiconfiguration(); httprequestprocessor = new httprequestprocessor(); networkconnectiondetector = new networkconnectiondetector(singlechatactivity.this); listbeanmessages = new arraylist<bean_message>(); adapter_message = new adapter_message(singlechatactivity.this, listbeanmessages, completeurlfriend); //setting adapter listview lv_message.setadapter(adapter_message); friendid = integer.parseint(frndid);//converting friendid integer //getting id of loggedin user id = sharedpreferences.getstring(prefs_registration.get_user_id, null); loggedinuserid = integer.parseint(id); // comparing loggedinuserid , friendid if (friendid < loggedinuserid) { smallerid = friendid; largerid = loggedinuserid; } else { smallerid = loggedinuserid; largerid = friendid; } sid = string.valueof(smallerid); lid = string.valueof(largerid); string combinedid = sid + lid; log.e("combined id", combinedid); md5stringroomid = convertpassmd5(combinedid); // encrypting combinedid generate room id log.e("md5stringroomid", md5stringroomid); api_message = apiconfiguration.getapi_message(); // getting api of messages url_feed_message = api_message + md5stringroomid; // md5string encrypted room id here log.e("url_feed_message", url_feed_message); //getting name of loggedinuser loggedinuser = sharedpreferences.getstring(prefs_registration.get_user_name, null); loggedinupper = uppercase(loggedinuser); //checking internet connection if (networkconnectiondetector.isconnectedtointernet()) { new messagetask().execute(); } else { showalertdialog(singlechatactivity.this, "internet connection", "please check internet connection .you don't have internet connection"); } //listening on events msocket.on(socket.event_connect, onconnect); msocket.on(socket.event_connect_error, onconnectionerror); msocket.on(socket.event_disconnect, ondisconnect); msocket.on("send:notice", onreceive); // listening event receiving messages msocket.connect(); // explicitly call connect method establish connection here msocket.emit("subscribe", md5stringroomid); // on clickinh edit text emoji panel hidden edmessage.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { hideemoji = true; hideemojipopup(hideemoji); showkeyboard(edmessage); } }); //handling click event on drawableleft , drawableright inside emojiconedittext edmessage.setontouchlistener(new view.ontouchlistener() { @override public boolean ontouch(view view, motionevent event) { final int drawable_left = 0; final int drawable_top = 1; final int drawable_right = 2; final int drawable_bottom = 3; if (event.getaction() == motionevent.action_up) { //handling drawableright if (event.getrawx() >= (edmessage.getright() - edmessage.getcompounddrawables()[drawable_right].getbounds().width())) { // action here toast.maketext(getapplicationcontext(), "clicked", toast.length_short).show(); message = edmessage.gettext().tostring().trim(); // spannable s = getsmiledtext(getapplicationcontext(),message); // log.e("spannable", string.valueof(s)); // encoding emoji unicode characters string toserver = stringescapeutils.escapejava(message); //to find current time in timestamp format date d = new date(); final long time = d.gettime(); log.e("time", string.valueof(time)); log.e("to server", toserver); log.e("sending", "sending data-----" + message); if (!message.equals("")) { edmessage.settext(" "); jsonobject jsonobject = new jsonobject(); try { jsonobject.put("room_id", md5stringroomid); jsonobject.put("user", loggedinupper); jsonobject.put("id", friendid); jsonobject.put("message", toserver); jsonobject.put("date", time); jsonobject.put("status", "sent"); } catch (jsonexception e) { e.printstacktrace(); } // isself = true; // boolean isself set true sender of message logged in user i.e. //attempttosend(loggedinupper, message, isself); msocket.emit("send", jsonobject); // owner i.e loggedin user sending message /* msg = new bean_message(); msg.setmessagestatus(status.sent); listbeanmessages.add(msg); adapter.notifydatasetchanged();*/ } else { runonuithread(new runnable() { @override public void run() { toast.maketext(getapplicationcontext(), "please enter text", toast.length_long).show(); } }); } return true; } //handling drawable left if (event.getrawx() <= (edmessage.getcompounddrawables()[drawable_left].getbounds().width())) { // action here toast.maketext(getapplicationcontext(), "clicked", toast.length_short).show(); hidekeyboard(); // hiding keyboard showemojipopup(!showemoji); return true; } } return false; } }); setemojiconfragment(false); getwindow().setsoftinputmode(windowmanager.layoutparams.soft_input_state_hidden); // hiding soft keyboard } // converting first lowercase letter of every word in uppercase string uppercase(string source) { stringbuffer res = new stringbuffer(); string[] strarr = source.split(" "); (string str : strarr) { char[] stringarray = str.trim().tochararray(); stringarray[0] = character.touppercase(stringarray[0]); str = new string(stringarray); res.append(str).append(" "); } return res.tostring().trim(); } // method set panel of emoticons in fragment private void setemojiconfragment(boolean usesystemdefault) { // replacing existing fragment having id emojicons fragment of emoticons library containing emoticons getsupportfragmentmanager().begintransaction().replace(r.id.emojicons, emojiconsfragment.newinstance(usesystemdefault)).commit(); } // hiding keyboard public void hidekeyboard() { inputmethodmanager inputmanager = (inputmethodmanager) getsystemservice(this.input_method_service); inputmanager.hidesoftinputfromwindow(getcurrentfocus().getwindowtoken(), inputmethodmanager.hide_not_always); } public void showemojipopup(boolean showemoji) { display display = getwindowmanager().getdefaultdisplay(); point size = new point(); display.getsize(size); deviceheight = size.y; log.e("device height", string.valueof(deviceheight)); framelayout = (framelayout) findviewbyid(r.id.emojicons); framelayout.getlayoutparams().height = (int) (deviceheight / 2.5); // setting height of framelayout framelayout.requestlayout(); framelayout.setvisibility(view.visible); setheightofemojiedittext(); } //setting height of emojiconedittext programmatically public void setheightofemojiedittext() { viewgroup.layoutparams lp = edmessage.getlayoutparams(); lp.height = 100; edmessage.setlayoutparams(lp); view v = (view) findviewbyid(r.id.view); v.setvisibility(view.visible); } // hiding framelayout containing list of emoticons public void hideemojipopup(boolean hideemoji) { framelayout framelayout = (framelayout) findviewbyid(r.id.emojicons); framelayout.setvisibility(view.gone); } //show soft keyboard public void showkeyboard(edittext edittext) { inputmethodmanager imm = (inputmethodmanager) getsystemservice(context.input_method_service); imm.showsoftinput(edittext, inputmethodmanager.show_implicit); setheightofemojiedittext(); } // event listeners private emitter.listener onconnect = new emitter.listener() { @override public void call(object... args) { log.e("socket", "connected"); } }; private emitter.listener onconnectionerror = new emitter.listener() { @override public void call(object... args) { log.e("error", "error in connecting server"); } }; private emitter.listener ondisconnect = new emitter.listener() { @override public void call(object... args) { log.e("disconnect", "socket disconnected"); } }; // event listener receiving messages private emitter.listener onreceive = new emitter.listener() { @override public void call(final object... args) { log.e("receive", "bean_message received"); runonuithread(new runnable() { @override public void run() { jsonobject data = (jsonobject) args[0]; log.e("data", string.valueof(data)); try { jsonarray ops = data.getjsonarray("ops"); log.e("jsonarray", ops.tostring()); (int = 0; < ops.length(); i++) { jsonobject object = ops.getjsonobject(i); string roomid = object.getstring("room_id"); log.e("roomid", roomid); // getting room id json array log.e("md5roomid", md5stringroomid); // getting room id have created using logged in user id , room id of user through chat has done //comparing room ids if (md5stringroomid.equals(roomid)) { string sendername = object.getstring("user"); log.e("sender name", sendername); string senderid = object.getstring("id"); log.e("senderid", senderid); string date = object.getstring("date"); // getting timestamp value in form of string long time = long.parselong(date); //converting string long string t = getdatefromtimestamp(time); // getting date , time timestamp log.e("datereceived", date); // jsonobject message = object.getjsonobject("message"); string unicodemessagereceived = object.getstring("message"); //decoding unicode characters emoji string messagereceived = stringescapeutils.unescapejava(unicodemessagereceived); log.e("bean_message received", messagereceived); string loggedinusername = sharedpreferences.getstring(prefs_registration.get_user_name, null); //string loggedinusername = almachatdatabase.getusername(); //if message sent owner other webapp ,then need check whether sender loggedinuser in app or not , right align messages . if (loggedinusername.equalsignorecase(sendername)) { isself = true; msg = new bean_message(sendername, messagereceived, isself); msg.setmessagestatus(status.sent); msg.settime(t); listbeanmessages.add(msg); // log.e("list elements", string.valueof(listbeanmessages)); adapter_message.notifydatasetchanged(); playbeep(); } else { isself = false; msg = new bean_message(sendername, messagereceived, isself); msg.settime(t); listbeanmessages.add(msg); log.e("list elements", string.valueof(listbeanmessages)); adapter_message.notifydatasetchanged(); playbeep(); } } } } catch (jsonexception e) { e.printstacktrace(); } } }); } // playing sound when message sent other public void playbeep() { try { uri notification = ringtonemanager.getdefaulturi(ringtonemanager.type_notification); ringtone r = ringtonemanager.getringtone(getapplicationcontext(), notification); r.play(); } catch (exception e) { e.printstacktrace(); } } }; @override public void onemojiconbackspaceclicked(view view) { emojiconsfragment.backspace(edmessage); } @override public void onemojiconclicked(emojicon emojicon) { emojiconsfragment.input(edmessage, emojicon); } //getting old messages of user public class messagetask extends asynctask<string, string, string> { @override protected string doinbackground(string... strings) { string response = httprequestprocessor.getrequestprocessor(url_feed_message); return response; } @override protected void onpostexecute(string s) { log.e("responsemessage", s); try { jsonarray jsonarray = new jsonarray(s); parsejsonfeed(jsonarray); } catch (jsonexception e) { e.printstacktrace(); } } } // encrypting string md5 public static string convertpassmd5(string pass) { string password = null; messagedigest mdenc; try { mdenc = messagedigest.getinstance("md5"); mdenc.update(pass.getbytes(), 0, pass.length()); pass = new biginteger(1, mdenc.digest()).tostring(16); while (pass.length() < 32) { pass = "0" + pass; } password = pass; } catch (nosuchalgorithmexception e1) { e1.printstacktrace(); } return password; } public void showalertdialog(context context, string title, string message) { alertdialog dialog = new alertdialog.builder(context).create(); //setting dialog title dialog.settitle(title); //setting dialog message dialog.setmessage(message); //setting ok button dialog.setbutton("ok", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { } }); dialog.show(); } // parsing json array corresponds old chat messages public void parsejsonfeed(jsonarray jsonarray) { (int = 0; < jsonarray.length(); i++) { try { jsonobject jsonobject = jsonarray.getjsonobject(i); string roomid = jsonobject.getstring("room_id"); log.e("roomid", roomid); log.e("md5roomid", md5stringroomid); // if room id(created using id of logged in user , id of friend) matches room id obtained json string if (md5stringroomid.equals(roomid)) { string username = jsonobject.getstring("user"); log.e("name", username); string loggedinusername = sharedpreferences.getstring(prefs_registration.get_user_name, null); //string loggedinusername = almachatdatabase.getusername(); log.e("loggedinuser", loggedinusername); //if message sent owner other webapp ,then need check whether sender loggedinuser in app or not , right align messages . if (loggedinusername.equalsignorecase(username)) { string message = jsonobject.getstring("message"); log.e("message", message); string date = jsonobject.getstring("date"); long time = long.parselong(date); string t = getdatefromtimestamp(time); log.e("timec", t); log.e("date", date); isself = true; msg = new bean_message(username, message, isself); msg.settime(t); listbeanmessages.add(msg); adapter_message.notifydatasetchanged(); //playbeep(); } else { //jsonobject jsonmessage = jsonobject.getjsonobject("message"); string message = jsonobject.getstring("message"); string date = jsonobject.getstring("date"); long time = long.parselong(date); string t = getdatefromtimestamp(time); log.e("timec", t); log.e("date", date); isself = false; msg = new bean_message(username, message, isself); msg.settime(t); listbeanmessages.add(msg); adapter_message.notifydatasetchanged(); // playbeep(); } } } catch (jsonexception e) { e.printstacktrace(); } } } // converting timestamp string private string getdatefromtimestamp(long time) { //string date = (string) dateformat.format("dd-mm-yyyy hh:mm a", time); string date = (string) dateformat.format("hh:mm a", time); return date; } @override public boolean oncreateoptionsmenu(menu menu) { log.e("option menu","called"); menuinflater inflater = getmenuinflater(); inflater.inflate(r.menu.menu_chat_activity, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case r.id.action_viewcontacts: return true; case r.id.action_media: return true; case r.id.action_search: return true; case r.id.action_block: return true; case r.id.action_email_chat: return true; case r.id.action_clear_chat: return true; case r.id.action_attach: return true; default: return super.onoptionsitemselected(item); } } }
androidmanifest
<activity android:name=".activity.singlechatactivity" android:theme="@android:style/theme.holo"></activity> </application>
"double-check have set app theme holo.light. can't explain causing problem, able reproduce it. after experimenting changes between fragmentactivity , appcompatactivity, accidentally ran fragmentactivity , theme set theme.appcompat.light. created behavior seeing, oncreateoptionsmenu() not called."
as side issue, should fix oncreateoptionsmenu() call through super noted in documentation: "deriving classes should call through base implementation".
originaly answered here
Comments
Post a Comment