Reputation: 2127
I have multiple activities in which I want to use same code in those activity. I finished it with having same bunch of code in each activity. How can minimize this redundant code. For doing this I dont want to create object and use it's methods for removing redundancy...
Plz help... Thank U....
Upvotes: 0
Views: 541
Reputation: 55517
You can can create a "BaseActivity" and include a lot code in that single class and then simply create classes and extend that "BaseActivity".
Here is what I think you are looking for:
public class BaseActivity extends Activity {
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.donate:
//something
break;
case R.id.about_menuitem:
//something
break;
case R.id.exit:
finish();
break;
default:
return true;
}
return true;
}
}
I created a class called "BaseActivity", in this class I have my Android options menu and I also extend "Activity". Since I extended "Activity" and have my options menu in this class, I can now use this same menu code for all my other classes.
I just simply create my new classes and extend them with "BaseActivity":
public class SomeOtherActivity extends BaseActivity {
//new code here
}
Now the class called "SomeOtherActivity", will inherit my menu code and also "Activity".
Please try this out and let me know is this helps!
Upvotes: 5
Reputation: 10785
the solution is simple: extends the class Activity, and add him all the methods you want.
(I usually call this class BaseActivity for instance)
then, when you are developing new activity - instead of extend the class Activity - extends the class BaseActivity you've made, which contain the methods you added..
public class BaseActivity extends Activity
{
protected int mSomeValue;
protected void someMethod1()
{
}
protected void someMethod2()
{
}
protected void someMethod3()
{
}
}
class SomeActivity extends BaseActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
someMethod1();
}
}
class SomeActivity2 extends BaseActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
someMethod1();
}
}
Upvotes: 5