ActionBar: setting button not appear in actionbar on samsung device - android

I implement layout for actionbar, including one button and other is setting button. I view in preview window (Intellij IDEA 13) I see as I expected but not on real device (samsung note 3).
Here is my layout:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- chat list. should appear as action button -->
<item android:id="#+id/action_chat_list"
android:icon="#drawable/ic_menu_chat_list"
android:title="#string/action_chat"
android:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
In Preview windows. I see as I expected:
But when I run on real device (Samsung Note 3).I cannot see Setting button:
I cannot understand why. Please tell me how to fix this.
Thanks :)

It because samsung has still a menu button. AFAIK there is no workaround for this

Because you got the options button down to the left of your homebutton. When you thouch it the overflow menu will show on the screen. I guess it implemented in the background so it doenst show on devices that have a "real hardware" options button.
Heres a picture of the button i found on the web. http://cdn.webcazine.com/wp-content/uploads/2012/06/samsung_galaxy_s3_option_keys1.jpg?00d8d4

As #Blackbelt has mentioned, because samsung has a menu button, so actionbar will automatically hide this. And I successfully follow this link to fix this problem. This really a small hack because you use java reflection api to change value of private attribute.
You put this code first when you start to run your application. You can subclass Application and put this code in onCreate
public class MyApplication extends Application {
private static final String TAG = "MyApplication";
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
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
}
}
}
And you declare this class in your android manifest file under application tag:
<application
android:label="#string/app_name" android:icon="#drawable/ic_launcher" android:allowBackup="true"
android:name=".MyApplication">
</application>
Hope this help :)

Related

How to implement event listeners on app shortcut icon?

I would like to create an app that deals with background pictures of the a user device. But when a user clicks the shortcut icon, the background should change without opening the app and the icon should be somehow animated.
Let's consider this application in Itel:
Before I click on the app shortcut icon
And after click, the app doesn't open but the background changes and the icon animates(see the picture):
How can someone achieve this?
AFAIK we cannot change app icon at runtime. My guess, The icon in the example above may be a widget
About changing background wallpaper (or performing a particular task): I think we can create a launcher activity (a transparent one/without setContentView()) which will finish() itself after triggering a background service that changes the wallpaper (or perform any other task). According to my opinion, this can be a solution for the scenario above though I haven't tried it personally
Best regards, Happy coding :)
tl;dr You can't change it because the icon of your app is registered in the Android Manifest that ships with it.
From the documentation:
Icons and labels
A number of manifest elements have an icon and label attributes for
displaying a small icon and a text label, respectively, to users for
the corresponding app component.
That means that your app will always have the same icon since the manifest cannot be changed in runtime. So my guess is that the app you reference is a system app, with system privileges.
The only icons that you can change are the shortcuts your app creates using this permission:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
To create a shortcut, please check this answer: https://stackoverflow.com/a/40446734/1574250
To change the background when clicking in your app icon, here is an example (in this example I'm only changing the background color when the app opens):
Class:
public class YourActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set you app icon
setColorWallpaper();
// Finish the activity
finish();
}
/**
* Sets the color wallpaper to the color value in the Clipboard, or to a random color.
*/
private void setColorWallpaper() {
// Try to get the color parameter from the clipboard
Integer colorParam = null;
try {
colorParam = ColorClipboardParameter.getColor(getApplication());
} catch (Exception ignored) {
// An unexpected exception while trying to get the color code from the clipboard
// can crash the app at startup. Ignore any exceptions, we will generate a random
// color anyway.
}
// If there is no valid color value in the clipboard, generate a random color
final int color = (colorParam != null) ? colorParam : GoodRandomColor.nextColor();
try {
// Set the color wallpaper
ColorWallpaper.setColorWallpaper(this, color);
// Success: copy the color code to the clipboard
Utils.copyText(this, Utils.colorToHex(color));
// Go to the home screen
Utils.goHome(this);
} catch (IOException e) {
// Write the stack trace to System.err and copy the reason of the failure to clipboard
e.printStackTrace();
Utils.copyText(this, e.toString());
}
}
}
Manifest:
<application
android:fullBackupContent="true"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:installLocation="auto"
android:label="#string/app_name"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".YourActivity"
android:excludeFromRecents="true"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
Check this project for more info: https://github.com/appgramming/LoneColor-Android

Simple Android SearchView not functioning properly

I am trying to follow the search interface manual from android.com. I have few problems and I am not sure what I did wrong exactly.
If you want to look, here is the project as zip file.
1- The android:hint is not visible when I touch search icon. It comes empty. Why? If I set it programmatically it works eg. searchView.setQueryHint(getString(R.string.search_hint)); Why it doesn't work from XML?
2- Search field does not get focus and keyboard does not appear automatically when I touch search icon. I need to touch to the search textfield to get focus. I believe it should get focus automatically?
3- When I write something and touch the search icon on the keyboard. I do not see any log entries logged at logcat window. What is missing?
4- (SOLVED) I tried android:iconifiedByDefault="false" in XML and also searchView.setIconifiedByDefault(false); and it is always iconified when I start the application. Why is that happening?
I found out that iI need to remove collapseActionView from app:showAsAction otherwise setIconifiedByDefault(false) does not work. Also if you remove collapseActionView and set setIconifiedByDefault(false) then it never collapses.
I am guessing I missed something somewhere but I am not sure exactly what...
So below are the steps I followed:
I started a new project with 'Basic Activity' in Android Studio 3.
It has a ready toolbar and 'Hello World' in the middle.
Then to xml folder I added the searchable.xml file with contents:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="Search hint text"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer">
</searchable>
Then changed AndroidManifest.xml file and added an activity:
<activity android:name=".SearchableActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
Then created a simple SearchableActivity.class. Just to log some lines.
package com.test.myapplication;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class SearchableActivity extends ListActivity {
private static String TAG = SearchableActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
Log.d(TAG, "handleIntent");
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
}
Then added to existing menu_main.xml the necessary item:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.test.myapplication.MainActivity">
<item android:id="#+id/search"
android:title="#string/app_name"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.widget.SearchView" />
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
Update: If I change to app:actionViewClass="android.support.v7.widget.SearchView" and also in MainActivity.class if I import import android.support.v7.widget.SearchView; then when I click on the search icon, it shows default Search... text gets focus automatically. But does NOT show hint from XML and still there are no log entries when I submit any information.
UPDATE:
I realized that if I put the intent-filter and the meta part under MainActivity I am getting the search intent inside main activity. But I don't understand why it does not start the SearchableActivity. Because manual page for SearchView clearly says:
When a user executes a search from the search dialog or widget, the system starts your searchable activity and sends it a ACTION_SEARCH intent.
Use this
app:actionViewClass="android.support.v7.widget.SearchView"
Instead of this
app:actionViewClass="android.widget.SearchView"
Apparently all I needed to do was to forward the intent to correct activity from onCreateOptionsMenu()
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName componentName = new ComponentName(this, SearchableActivity.class);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
if (searchManager != null)
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName));

Cannot see Options Menu on Android Device

I've got an application written with minSdkVersion="8" and targetSdkVersion="19", because is so simple and I need it to be used on low level android devices.
The problem is when I try to use it in an Android 4+ device. I cannot see the Options menu.
When I use the app in the Emulator, I use the "Menu" button, and I can see it. But not in my tablet or mobile phone (both with 4+ version).
Okay, let's see the code:
In the manifest.xml file I have this (I think the problem is the theme...).
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light" >
<activity
android:name="com.clv.app2.MainActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme">
And I have a simple OnCreateOptionsMenu like this in MainActivity... (I have defined only two options).
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
Can anyone can help me to see where is the problem with this?
Thank you in advance.
EDIT:
option_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/scan"
android:icon="#android:drawable/ic_menu_search"
android:title="#string/connect"/>
<item
android:id="#+id/discoverable"
android:icon="#android:drawable/ic_menu_mylocation"
android:title="#string/discoverable"/>
EDIT:
Okay. I have been reading other entries in forum, and I see that there are devices that have not a menu key (to show options menu), and from 3+ version it is not required to have it.
When I execute my application in an Android device less than 3 version, I have that physical button, and it works. In an Android device more than 3 version (I have one with 4+ version), that button does not exists, and there are no way to make the options menu visible.
My question is... Do I have to put a button in screen on 3+ devices with no "physical menu button", to use it when I want to see the options menu???
I have found the problem that make the application not work on 4+ devices.
In the onCreate method I have in my MainActivity, I have this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "En onCreate...");
// Preparo texto cabecera de pantalla
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
R.layout.custom_title);
If I take all that code out, leaving only setContentView it works.
It think the issue is in your activity schema.
First change schema in AndroidManifest to yours:
<activity
android:name="com.clv.app2.MainActivity"
android:label="#string/app_name"
android:theme="#style/MyTheme">
Create styles_mytheme.xml in values folder with lines:
<resources>
<style name="Theme.MyTheme" parent="#android:style/Theme"/>
</resources>
Or just add next line to any styles files:
<style name="Theme.MyTheme" parent="#android:style/Theme"/>
Create folder values-v11 and create file there styles_mytheme.xml:
<resources>
<style name="Theme.MyTheme" parent="#android:style/Theme.Holo"/>
</resources>
So basically your Activity will use default theme for old devices and Holo for devices from v11.
I think its not a problem of theme, but while creating your project just make changes like:
Minimum Required SDK: API8: Android 2.2(Froyo)
Target SDK: API17:Android 4.2(Jelly Bean)
Compile With: API8: Android 2.2(Froyo)
Theme: None
Hope it will work.

How do I change the android actionbar title and icon

I'm trying to do some things on the ActionBar in Android.
I've already added new items in the right side of the action bar.
How can I change the left side of the action bar? I want to change the icon and the text, and I want to add a "Back Button" in the action bar for the other screens
This is very simple to accomplish
If you want to change it in code, call:
setTitle("My new title");
getActionBar().setIcon(R.drawable.my_icon);
And set the values to whatever you please.
Or, in the Android manifest XML file:
<activity android:name=".MyActivity"
android:icon="#drawable/my_icon"
android:label="My new title" />
To enable the back button in your app use:
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
The code should all be placed in your onCreate so that the label/icon changing is transparent to the user, but in reality it can be called anywhere during the activity's lifecycle.
To make a single icon be usable by all your action bars you can do this in your Android Manifest.
<application
android:logo="#drawable/Image">
...
</application>
You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this
getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
In Android 5.0 material design guidelines discourage the use of icon in actionBar
to enable it add the following code
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
credit goes to author of this article
If you want to change the Action bar title just give the following 1 line code in the onCreate() of your Activity
getActionBar().setTitle("Test");
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getString(R.string.titolo));
actionBar.setIcon(R.mipmap.ic_launcher);
actionBar.setDisplayShowHomeEnabled(true);
You can change the icon in your by adding whatever icon you want to your respective drawable folders, then changing this line in your AndroidManifest.xml file:
android:icon="#drawable/ic_launcher"
to match whatever the name of your icon is in there. Or put your icon as ic_launcher, if they're the same icon. As for what it says, add or change whatever strings match up to that in your res/values/strings.xml file. Then, once again in your AndroidManifest.xml file, change this line:
android:label="#string/app_name"
to whatever the string you have in their. You'll have to do this for the application as a whole, and whichever activities you want, but the lines are the same.
Hope this helps.
For that, you can do it in 2 ways: XML or Java. See here: How to change the text on the action bar
So:
XML:
<activity android:name=".Hello_World"
android:label="This is the Hello World Application">
</activity>
Java:
public class TitleBar extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
if ( customTitleSupported ) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
}
final TextView myTitleText = (TextView) findViewById(R.id.myTitle);
if ( myTitleText != null ) {
myTitleText.setText("NEW TITLE");
// user can also set color using "Color" and then "Color value constant"
// myTitleText.setBackgroundColor(Color.GREEN);
}
}
}
For set Title :
getActionBar().setTitle("Title");
For set Icon :
getActionBar().setIcon(R.drawable.YOUR_ICON_NAME);
Add the below code inside an onCreate function in your activity.
setTitle("NewName");
I used the following call inside onNavigationItemSelected:
HomeActivity.this.setTitle(item.getTitle());
Go to manifest in which specific activity you want to change Action bar Title name and write
android:label="Title name"
This work for me:
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeAsUpIndicator(R.mipmap.baseline_dehaze_white_24);
The action bar title will, by default, use the label of the current activity, but you can also set it programmatically via ActionBar.setTitle().
To implement the "Back" (more precisely, "Up") button functionality you're talking about, read the "Using the App Icon for Navigation" section of the Action Bar developer guide.
Finally, to change the icon, the guide covers that as well. In short, the action bar will display the image supplied in android:icon in your manifest's application or activity element, if there is one. The typical practice is to create an application icon (in all of the various densities you'll need) named ic_launcher.png, and place it in your drawable-* directories.
I got non-static method setTitle(CharSequence) cannot be referenced from a static context error because I used setTitle() in static PlaceholderFragment class. I solved it by using getActivity().getActionBar().setTitle("new title");
You can also do as follow :
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
setSupportActionBar(toolbar)
setTitle("Activity 2")
}
Go to AndroidManifest.xml file.
Find the <application> tag
There you can see a attribute
android:label="#string/app_name"
Now go to res > values > strings.xml
Change the
<string name="app_name">MainActivity</string>
to
<string name="app_name">Your Desired Name</string>
Example
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SubmitForm">
</activity>
</application>
strings.xml
<resources>
<string name="app_name">Your Desired Name</string>
<string name="action_settings">Settings</string>
</resources>

Start a Dummy Activity

I recently started Android coding and wanted to create a little program for changing the screen brightness...
Well.. i know there are already some questions about it, but i tried everything suggested here and really dunno how i can solve my problem :)
I understood that you have to "refresh" the screen after setting brightness. And at this point my problem starts... I've created some kind of dummy activity and also have an intent in my main activity, but it seems like the intent dont sart the dummy activity... Heres the relevant part of my main activity:
button1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 255);
Intent in = new Intent(Test.this,DummyBrightnessActivity.class); //it is working...
startActivity(in); //it is working...
}
and the dummy code:
public class DummyBrightnessActivity extends Activity{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.finish();
}
}
the manifest.xml:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".Test"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.Test.DummyBrightnessActivity"
android:taskAffinity="com.Test.Dummy"
android:excludeFromRecents="true"
android:theme="#style/EmptyActivity"></activity>
</application>
maybe relevant, the styles.xml:
<resources>
<style name="EmptyActivity" parent="android:Theme.Dialog">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">#android:style/Animation.Toast</item>
<item name="android:background">#00000000</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:colorForeground">#000</item>
<item name="android:backgroundDimEnabled">false</item>
<item name="android:windowIsFloating">true</item>
</style>
</resources>
oh, btw... I dont get any errors... The dummy just wont start (I think so, because when i run it without android:excludeFromRecents="true" then it wont appear in the recent apps list.
I hope someone can help me...
Have a nice day
//EDIT: Well... it looks like the code is working properly xD
Just relooked and put some text instead of the "finish()" and the activity run properly... but i thought that the finish have to be there :/
Maybe you have any suggestions how to "reset" the screen instead? Looks like i understood one of the tutorials wrong...
//EDIT2:
Well... I cant post an answer to my own question in the first 8hours:D
So i post it in here:
Thank you all for the help and tips, but now i found the solution for myself :D
this one: Refreshing the display from a widget?
the part "kicking off an empty activity and executing the WindowManager refresh" is working for me.
i came across this before asking here, but back then i just couldnt get it to work :D
So, anyways, thank you very much ;)
This was just an example of hard it can be to code "a little, fast-coded beginner app" ;)
You may also want to consider calling invalidate() on your View instead of launching and closing a new one.
I am not sure if it will work for this scenario, as I have not tried changing the screen brightness. However, as per http://developer.android.com/reference/android/view/View.html#invalidate(), calling invalidate() on a view will cause onDraw() to be called, which sounds like what you want.
I think this should work. I use this when I am moving from one page to another. It simply identifies the class and starts the activity, running whatever your new activity is going to do.
public void onClick(View v) {
// (IN THIS EXAMPLE) IDENTIFIES WHAT IS BEING PRESSED
if(v.getId() == R.id.activity) {
// STARTS THE OTHER ACTIVITY
Intent i = new Intent(this,Activity2.class);
this.startActivity(i);
}
Also, remove finish(); because your activity initializes and closes at the same time.
Make sure that you set the content view (setContentView(R.layout.main);) so you can tell whether or not the activity you started actually brings you to the page you want.
EDIT: You say the button press isn't detected. Try implementing the OnClickListener directly to your activity android import it like this.
public class MyApplication extends Activity implements OnClickListener {
Also, make sure your button is properly initialized. Try removing this: button1.setOnClickListener(new OnClickListener(), and then add this to your code:
button1 = (Button) findViewById(R.id.activity);
button1.setOnClickListener(this);

Categories

Resources