In one of my Android Application I need to keep the title bar same but the view that is shown in the rest of the screen changes. So, I have taken different Activity for all the views that I need to show and set the title bar in every Activities onCreate method.
Now, the problem is that I have a button in the title bar and need to perform certain action on its click event. Writing the same event handling code in every Activity class is very cumbersome. Is there any other way out that whenever there is a click event on that button of the title bar then we can have the same functionality without writing the same code in all the Activity classes.
Can we use ViewGroup for that? I don't have much idea about ViewGroup. Is that possible with ViewGroup?
If anyone knows the solution then please let me know.
Thanks & Regards
Sunil
If you are sharing view elements and functionality amongst several classes extending Activity, you might want to consider making a common superclass to handle this overlap.
The best solution is to keep a base activity like this.
public class HeaderBaseActivity extends AppCompatActivity{
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
mAppPreferences = AppUtil.getAppPreferences(this);
item_patients = menu.findItem(R.id.item_patients);
setBatchCountOnMenu(0);
RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
mRealm = Realm.getInstance(realmConfig);
mDotor = new Gson().fromJson(mAppPreferences.getString(Constants.SETTINGS_OBJ_DOCTOR, ""), Doctor.class);
mAppPreferences = AppUtil.getAppPreferences(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
/* DialogUtility.showShortToast(this, " Main manu Action Logout");*/
SharedPreferences.Editor Editor = mAppPreferences.edit();
Editor.putBoolean(Constants.SETTINGS_IS_LOGGED_IN, false);
Editor.apply();
clearRealmDB();
Intent loginIntent = new Intent(HeaderBaseActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(loginIntent);
finish();
break;
case R.id.item_patients:
System.out.println("current activity "+getApplicationContext());
Intent mPatientListIntent = new Intent(HeaderBaseActivity.this, PatientSummaryInfoActivity.class);
mPatientListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mPatientListIntent);
break;
case R.id.action_doctor_profile:
openDialogOfDoctorProfile();
break;
}
return super.onOptionsItemSelected(item);
}
}
Your other activities can extend the above activity like this:
public class MainActivity extends HeaderBaseActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
}
}
Related
After clicking a button to open a new Activity using this method:
setContentView(R.layout.activity_comunidades01);
The second Activity still display the same menu as the previous one.
I have already readed serval methods to fix it as the one related in here:
Android: How to enable/disable option menu item on button click?
But I discovered that the methods to intialize and create the menu are never called. I even try to follow this other link without success:
onCreateOptionsMenu is never called
I even deleted all the items in the menu.xml for this activity but still displaying the previous activity options.
I also clarify I am using android 4.4 as target API but level 10 as a minimum one since some devices that will be used are running android 2.3.
My second Activity is like this:
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_SecondActivity);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
System.out.println("EN ON PREPARE OPTIONS MENU");
(menu.findItem(R.id.sincronizar)).setEnabled(false);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
System.out.println("EN ON CREATE OPTIONS MENU");
getMenuInflater().inflate(R.menu.SecondActivity, menu);
return true;
}
}
To start second activity use this:
Button bt = (Button)findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
//finish(); //if you want to close FirstActivity after showing SecondActivity
}
});
After clicking a button to open a new Activity using this method:
setContentView(R.layout.activity_comunidades01)
This is not how you open another activity!
This way you only change the content of the current activity, nothing else.
Use Activity.startActivity() or Activity.startActivityForResult() as described in the docs to start another activity.
I'm new to Android Preferences which I am using for a settings menu and I just had a few questions. I looked on the API site and couldn't find a way to add action to them. I have an Activity:
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, false);
addPreferencesFromResource(R.xml.preferences);
}
}
}
which works fine, it displays my xml PreferenceScreen page which contains 4 Preference tags. My question is how do I add action when clicking on those preferences. For example I want a separate pop up window to be displayed where I can change a number value and for that to be saved each time I open the app. If someone could provide an example or something I would really appreciate it
I want a separate pop up window to be displayed where I can change a number value and for that to be saved
This is easy, you just have to make that Preference an EditTextPreference at your xml file like so:
<EditTextPreference
android:title="#string/title"
android:key="preferenceKey" />
You can customize it more: if you only want integers android:numeric="integer" , if you want to set the max length android:maxLength="3" and the default value android:defaultValue="10" . You don't have to do anything in the Java class
how do I add action when clicking on those preferences
If you want to add some more complicated action, use a Preference.OnPreferenceClickListener. You can use it like so:
Preference preference = // some preference
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener(){
#Override
public boolean onPreferenceClick(Preference p){
//do something
return false;
}
});
You can find more at this question. Hope this helps
PS. If you want to customize the preference a lot (i.e. not only the action onClick, but also the layout etc), you should consider creating a custom Preference, as said at another answer.
It sounds like what you are trying to do would be appropriately handled by creating a custom Preference. The Android docs has a decent tutorial on this: http://developer.android.com/guide/topics/ui/settings.html#Custom
Based on your requirement, you can work through intents for your preference tags. below is my example code in Menu.java: and also you can follow the developer tutorial at : http://developer.android.com/guide/topics/ui/settings.html#Custom
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.about:
/*Intent aboutIntent = new Intent(Menu.this, About.class);
startActivity(aboutIntent);*/
Intent aboutIntent = new Intent("com.example.myfirstapp.ABOUT");
startActivity(aboutIntent);
break;
case R.id.preference:
Intent prefsIntent = new Intent("com.example.myfirstapp.PREFS");
startActivity(prefsIntent);
break;
case R.id.exit:
finish();
break;
}
return false;
}
Code in About.java
public class About extends Activity {
TextView TV1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
TV1 = (TextView) findViewById (R.id.textView1);
}
}
I am new to android and dont know where should i write the actionlistner code for action bar buttons so that i don't need to write the action listner code in all activity.
Please look at below image: i have a menu.xml file for action bar menu and added in one of my activity via onCreateOptionMenu function. when user click on any of my button of action bar then i can track it via onOptionItemSelected function.
Problem-1: For all other activity, i can use same menu.xml file but do i need to override onCreateOptionMenu function of each activity.
Problem 2: Do i need to write onOptionItemSelected function code in all activity?
Please suggest me better solution of these problems.
Problem-1: For all other activity, i can use same menu.xml file but do i need to override onCreateOptionMenu function of each activity.
Problem 2: Do i need to write onOptionItemSelected function code in all activity?
You can create a 'base' Activity and implement the methods in that. Then all you need to do is make sure all other Activities extend the 'base' Activity.
Example (note I use ActionBarSherlock so my 'base' Activity initially extends ShelockFragmentActivity - that may not be the same in your case but this gives an example)...
public class MyBaseFragmentActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
// Handle menu selection here
}
}
Now any Activity that extends that 'base' Activity will automatically inherit the menu creation and item selection methods of the 'base' class.
public class ActivityA extends MyBaseFragmentActivity {
// No need to create the menu or handle item selection
}
Problem-1: For all other activity, i can use same menu.xml file but do i need to override onCreateOptionMenu function of each activity.
Yes, simply add your code to handle the menu options in a switch statement.
Problem 2: Do i need to write onOptionItemSelected function code in all activity?
Yes, for each activity that is using the action bar, you will need to override the onOptionItemSelected function and add your custom code.
For example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_watchlist:
Intent intent = new Intent(HomeActivity.this, WatchlistActivity.class);
intent.putExtra("username", currentUser.getUsername());
startActivityForResult(intent, 0);
return true;
case R.id.menu_history:
Intent intent2 = new Intent(HomeActivity.this, HistoryActivity.class);
intent2.putExtra("username", currentUser.getUsername());
startActivityForResult(intent2, 0);
return true;
case R.id.menu_scores:
// Scores only available with Facebook login
if (facebookLogin)
{
Intent scoreIntent = new Intent(HomeActivity.this, ScoresActivity.class);
scoreIntent.putExtra("username", currentUser.getUsername());
scoreIntent.putExtra("accessToken", accessToken);
Session session = Session.getActiveSession();
scoreIntent.putExtra("session", session);
startActivityForResult(scoreIntent, 0);
}
else
Toast.makeText(getApplicationContext(), "Please login to Facebook to use this feature.", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_settings:
Intent intent3 = new Intent(HomeActivity.this, SettingsActivity.class);
intent3.putExtra("username", currentUser.getUsername());
startActivityForResult(intent3, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
I want to have a superclass activity that defines what basic menu items each activity should have in addition to their own.
Here is my code so far:
public abstract class SuperActivity extends FragmentActivity {
protected List<TextView> textView = new ArrayList<TextView>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentResource());
setTextViews(textView);
}
protected abstract void setTextViews(List<TextView> textViews);
protected abstract int getContentResource();
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menuitemsforallsubclasses, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.basicmenuitem1:
allSubclassActivitiesCanDoThis()
return true;
case R.id.basicmenuitem2:
allSubclassActivitiesCanDoThis2()
return true;
}
}
}
In the subclasses I would then just add something to onCreateOptionsMenu (an additional layout file) and onOptionsItemSelected, is that correct? Just want to make sure I am not on the wrong track here. Would it even be possible to load multiple layout file in the same activity?
FYI: In case you are wondering why I have a TextView array in the activity: In addition to this I want to have all TextViews of each subclass activity in an ArrayList, so that I can add listeners to all of them automatically so I know when something has changed in the activity or to do some other neat stuff.
Is what I am doing possible? Is it possible to load multiple menu layout files?
I am setting the action bar and item by the below code and the respective image1 is shown. When the user clicks on show bookmark screen action item, it goes to other activity. In that activity I want another item(SELECT BOOKMARK TYPE ) to be displayed in the place of SHOW BOOKMARK SCREEN. So I am thinking to managing it with abstract class by setting the respective things to true or false as shown below. But now I am unable to get two things.
1) How to differentiate in case 0 for both action items? as I am replacing the action item with one another.
2)How to get the dropdown for that SELECT BOOKMARK TYPE as exactly shown in the image 2.
Have seen few posts, but as I am somewhat new to android, I am unable to understand and get it done by adding the extra code to my present code. Can you please help me on this? Code snippets are appreciated. Thanks in advance.
public abstract class ActionActivity extends SherlockActivity {
protected boolean mIsShowBookmarkScreen = true;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if(mIsShowBookmarkScreen)
{
menu.add("SHOW BOOKMARK SCREEN")
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
else
{
menu.add(SELECT BOOKMARK TYPE);
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//This uses the imported MenuItem from ActionBarSherlock
switch(item.getItemId())
{
case 0:
Intent intent = new Intent(ActionActivity.this,BookmarkScreen.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
image 1:
image 2:
At least can someone please help on achieving second one. I got an idea on 1st problem.
1) Differentiate by using instanceof.
if (this instanceof ActivityA) {
// start Intent A
} else if (this instanceof ActivityB) {
// start Intent B
}
2) Add a Spinner as a custom ActionView.
<string-array name="items">
<item>SELECT BOOKMARK TYPE</item>
<item>TYPE-1</item>
<item>TYPE-2</item>
<item>TYPE-3</item>
</string-array>
MenuItem spinnerItem = menu.add(null);
spinnerItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
IcsSpinner spinner = new IcsSpinner(this, null);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.items, R.layout.sherlock_spinner_item);
adapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
spinnerItem.setActionView(spinner);
Note that I am using the kind of private IcsSpinner here to create the same look on SDK Version < 4.0. See this answer for details.
If you want to further customize the Spinner, you will probably need to create your own Adapter.