Overriding onCreateOptionsMenu from baseActivity class - java

I have a main class called BaseActivity which has a method
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
Now i extend this class like this...
public class MainActivity extends BaseActivity {
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
Log.d("Its called", "Kevin");
menuInflater.inflate(R.menu.othermenu, menu);
}
}
How would i override this method here, should it be a boolean or void.
Update:
public class FragmentClass extends android.support.v4.app.Fragment {
// How would i over-ride the onCreateOptionsMenu() here of BaseActivity.
}

Any overriding method needs to have the same signature as the method it is overriding. Don't forget to call super, like so:
public class MainActivity extends BaseActivity {
#Override
public boolean onCreateOptionsMenu( Menu menu ) {
if( super.onCreateOptionsMenu( menu ) ) {
Log.d("Its called", "Kevin");
getSupportMenuInflater().inflate(R.menu.othermenu, menu);
return true;
} else {
return false;
}
}
}

Related

How to call findViewById(R.id.textView) in another class than MainActivity?

I am new to Android.
I am trying to refer a View by Id from a separate class than MainActivity.
Note: My app has single activity.
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)//Activity Oncreate callback
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) //Oncreate Options_menu callback
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.option1:
//Here am calling a method from another class
SecondClass secondClassObject=new SecondClass();
secondClassObject.method1();
}
return true;
}
Second Class:
public class SecondClass {
public void method1(){
TextView tv1 = (TextView)findViewById(R.id.textView);
tv1.setText("");
}
}
How to refer to the textView by ID in the SecondClass? How to set the context as MainActivity in this SecondClass?
Add an Activity parameter for your method
public void method1(Activity act){
TextView tv1 = (TextView)act.findViewById(R.id.textView);
tv1.setText("");
}
From your activity define an Activity variable Activity act; so as to use it across other functions .Assign a value of your Activity to the variable act=this; and finaly use it on the function you want.
public class MainActivity extends AppCompatActivity {
Activity act;
#Override
protected void onCreate(Bundle savedInstanceState)//Activity Oncreate callback
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
act=this;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) //Oncreate Options_menu callback
{
act=this;
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.option1:
//Here am calling a method from another class
//SecondClass secondClassObject=new SecondClass();
//secondClassObject.method1();
SecondClass secondClassObject=new SecondClass();
secondClassObject.method1(act);
}
return true;
}
you can also pass the parent layout view
public void method1(View act){
TextView tv1 = (TextView)act.findViewById(R.id.textView);
tv1.setText("");
}
And call it like so
SecondClass secondClassObject=new SecondClass();
secondClassObject.method1(findViewById(R.id.your_parent_layout));
Avoid using passing Activity method if its not absolutely necessary to avoid possibilities of memory leaks.

How can I change option menu in different fragments?

I have a Fragment with menu:
public class FragmentA extends Fragment {
public FragmentA() {
setHasOptionsMenu(true);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_main_actions, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
I would like to change menu but it doesn't work and keep the old action menu
Fragment B is equals like above with different inflate XML menu.
public class FragmentB extends Fragment {
public FragmentB() {
setHasOptionsMenu(true);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.**action_ranking**, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
EDITED:
Can be useful to use different menu layout for different fragments and 1 menu layout for main activity and differents id
Put setHasOptionsMenu(true) in constructor and inflate fragment specific menu.
public class FragmentA extends Fragment {
public FragmentA() {
setHasOptionsMenu(true);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragmenta_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
menu in main activity
public class MainActivity extends Activity {
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
Can all be done via Fragment - no need to inflate menu from activity:
public class UpdateFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.update_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.navUpdateProfile:
showToast("navUpdateProfile");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
If you have several fragments that share the same menu with some exceptions.
class BaseFragment:Fragment(){
open var menuId = R.menu.default_menu
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true) // will apply to all children
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(menuId, menu) // will apply to all children except for overridden
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// all menu ids can be listed here unless specific to code in child
when (item.itemId) {
R.id.menu_option_1 -> {
// do something
}
R.id.menu_option_2 -> {
//do something
}
return false
}
}
class ChildFragment:BasFragment(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
menuId = R.menu.menu_2 // change to a different menu as desired here
}
}

ActionBarCompat can't find methods from the superclass

I'm following a tutorial on ActionBarCompat that also enables a search text area. I extended the ActionBarActivity from the v7 support lib. When I try to override these two methods it can't find them in the superclass. I went to source and looked at the superclass' methods and I can't locate them there as well. The two methods are onQueryTextSubmit and onQueryTextChange
This was the tutorial.
Any idea what I am doing wrong?
This is the error when I hover over the methods:
The method onQueryTextChange(String) of type MainActivity must override or implement a supertype method
public class MainActivity extends ActionBarActivity{
private SearchView mSearchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {
// Ignore
}
}
#Override
public boolean onQueryTextSubmit(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem searchItem=menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
mSearchView.setIconified(false);
return true;
}
return false;
}
It sounds like you are not implementing the class that is needed for those methods.
public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener
Make sure that you implemented SearchView.OnQueryTextListener.

How to call from supper-class method in subclass?

How from class BasicActivity call method stackAFragment from subclass Sub?
I want to have an opportunity to replace Fragment in my Activity Sub from any Activity that extends BasicActivity by using menu. I am going to create a method in Sub for each item menu. Here is a simple example how I see it:
public class BasicActivity extends FragmentActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.m_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.stad:
TabHost tabHost = (TabHost) getParent().findViewById(android.R.id.tabhost);
tabHost.setCurrentTab(4); //here is me Sub.class
//How to call method stackAFragment here?
break;
default:
return false;
}
return true;
}
}
Subclass:
public class Sub extends BasicActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub);
}
public void stackAFragment() {
Fragment f = new StadFr();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.the_frag, f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
Create an overridable method in BasicActivity (with an empty implementation for instance) and override it in Sub.
public class BasicActivity extends FragmentActivity {
protected void onTabChanged(){ }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.stad:
TabHost tabHost = (TabHost) getParent().findViewById(android.R.id.tabhost);
tabHost.setCurrentTab(4); //here is me Sub.class
onTabChanged();
break;
default:
return false;
}
return true;
}
public class Sub extends BasicActivity {
protected void onTabChanged() { stackAFragment(); }
....
}
You can make your BasicActivity class implement method stackAFragment() and override it in your subclass. You can also declare the method abstract in your BasicActivity which will then become also an abstract class.
super.stackAFragment(). But this method must be defined in your BasicActivity. It may be abstract if you want.
This should provide you with the wanted functionality:
Activity activity = getLocalActivityManager().getActivity( tabHost().getCurrentTabTag() );
if( activity instanceof Sub )
((Sub) activity).stackAFragment();

abstract activity causes findViewById() not to work

I have an abstract Activity as most of my activities share the same menu:
public abstract class ActivityBase extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menubar, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
//...
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//...
}
}
Now, when I use that class (inherit from it), the findViewById() method doesn't work anymore. Doesn't matter if I even inherit from it in that particular class, once it is somewhere in the inheritance tree, it doesn't work anymore. For example:
public class SomeOther extends ActivityBase {
}
public class Home extends Activity {
#Override
public void onCreate (Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.main);
Button b = (Button)findViewById(R.id.button); // fails, NullPointerException
}
What could be the cause of this, and even more importantly, how can I fix it?
In my case this work perfect (try this)...
public abstract class ActivityBase extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
//..
return true;
}
}
and
public class MyActActivity extends ActivityBase {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e("HI", "Hello");
TextView tv=(TextView)findViewById(R.id.Settings_phoneNumbersT1);
Log.e("HI", tv.toString());
}
}
and main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/Settings_phoneNumbersT1"
android:textSize="14sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff" android:text="Hellofffff"/>
</LinearLayout>
So, I don't think it is problem of Abstract ActivityBase class.
try this...
Button b = (Button)Home.this.findViewById(R.id.button);
its to make sure that your present class's findviewById is called and not the super class's..
The NullPointerException was caused someplace else and just manifested with that method. If you derive from Application and try to call getSharedPreferences, it fails, but you can't pinpoint it.

Categories

Resources