in action bar search icon wont show up - android

I'm following official android tutorials from Docant pdf book. For some reason my search icon won't show up. I included ic_action_search.png photos from holo_dark and im using holo light with dark action bar theme.
Here is code, no erros found by eclipse, min sdk is set to 11.
DisplayMessageActivity.java file
package com.example.myfirstapp1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="always" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>

I think your error is in your onCreate method, in this line:
setContentView(textView);
You should set the content view to the xml of your view, and not to a textview.
Your onCreate should look something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(the_name_of_your_xml_for_this_activity);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
}

I would recommend you to use actionbar library http://actionbarsherlock.com/
For better result on any actionbar related action

I think you need to defined it first in res/valuse/drawables.xml
<item name="ic_action_search" type="drawable">#android:drawable/ic_menu_search</item>
check the photo,
If you have a .bng photo you have to import it by another way to drawable than use
android:src="#drawable/ic_action_search"

Related

Using SearchView with AppCompatActivity results in UI glitches

I am trying to create an Android app with a search button in the Action Bar and when the user presses on the search button, then a search text box appears on the action bar, like in Google's Messenger app (see below).
I tried to implement it as shown below but my app looks like this:
There are a few problems with this. For example, the text reads "Search..." with the elipsis, unlike a simple "Search" without the elipsis, but by far the most concerning thing, is that there is no back button in the toolbar, the search button is pushed too far to the left, and the overflow button on the right has been pushed to the side. In addition, pressing the physical back button on my device does not collapse the searchview, it just exists to app.
Some of the code which I used to try to implement the search bar is below. I tried to set a SearchViewExpandListener as seen below so that the back button would appear when the search view is expanded, however it does not work.
EDIT: I also ran the app with breakpoints on my onMenuItemActionExpand and onMenuItemActionCollapsed methods, and I found out that these methods are in fact never called.
MainActivity.java
import android.content.Context;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// See above
MenuItemCompat.setOnActionExpandListener(searchItem, new SearchViewExpandListener(this));
MenuItemCompat.setActionView(searchItem, searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
Toast.makeText(MainActivity.this, "You searched " + s, Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return true;
}
// See above
private class SearchViewExpandListener implements MenuItemCompat.OnActionExpandListener {
private Context context;
public SearchViewExpandListener (Context c) {
context = c;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
((AppCompatActivity) context).getSupportActionBar().setDisplayShowHomeEnabled(true);
return false;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
((AppCompatActivity) context).getSupportActionBar().setDisplayShowHomeEnabled(false);
return false;
}
}
}
menu.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_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom"/>
<item android:id="#+id/action_about"
android:title="About"
app:showAsAction="never"/>
</menu>
It also appears that it is not just me who has this problem. This guide on implementing a SearchView appears to experience similar issues.
So what is the correct way to implement a search bar in an AppCompatActivity which results in a search bar like that in Google's Material Design guidelines and like that in their apps such as Google Messenger? I feel like I've been Googling endlessly for the past while, but I cannot find anything which helps me.
Use collapseActionView flag along with always in showAsAction on serchView menu item
app:showAsAction="always|collapseActionView"
The collapseActionView flag indicates how to display the widget when the user is not interacting with it: If the widget is on the app bar, the app should display the widget as an icon. If the widget is in the overflow menu, the app should display the widget as a menu item. When the user interacts with the action view, it expands to fill the app bar.

Simple Android app Can't get a blank activity to use non AppCompat theme

I've been going through the Android training tutorials and I can't seem to get a simple blank activity to apply the theme Theme.Holo.Light.
This is what I've done so far:
Set the minSdkVersion to 11 in gradle script and synced the project.
Applied the theme in the AndroidManifest.xml by setting:
android:theme="#android:style/Theme.Holo.Light"
Tried applying it at the application/activity level and by creating custom theme and setting the parent.
When running the app in the emulator it crashes with the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test.themetest3/com.example.test.themetest3.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
According to the documentation the default theme for 11+ API levels is Theme.Holo but I can't get it to work and I'm obviously missing something.
My activity insists on using AppCompat themes only. Do I need to extend some other class within my activity?
This is the activity code (generated by creating a blank activity).
package com.example.test.themetest3;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Thanks for your assistance :).
Your activity Extends AppCompatActivity, so you have to use AppCompatActivity themes. Use this in your styles.xml
parent="Theme.AppCompat.Light"
And if you also want to use Toolbar, you can get rid of ActionBar by using :
parent="Theme.AppCompat.Light.NoActionBar"

MainActivity.java action_settings cannot be resolved or is not a field

This is the only error I have now in my MainActivity.java.
The line "if (id == R.id.action_settings)" which is created by eclipse gives the error :"action_settings cannot be resolved or is not a field"
I appreciate your help to solve it
package chapter.two.hello_world;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
WorldGen earth = new WorldGen("Earth", 5973, 9.78);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setStartUpWorldValues();
}
protected void setStartUpWorldValues(){
earth.setPlanetColonies(1);
earth.setPlanetMilitary(1);
earth.setColonyImmigration(1000);
earth.setBaseProtection(100);
earth.turnForceFieldOn();
}
protected void setStartUpScreenText(){
TextView planetNameValue = (TextView)findViewById(R.id.dataView1);
planetNameValue.setText(earth.planetName);
TextView planetMassValue = (TextView)findViewById(R.id.dataView2);
planetMassValue.setText(String.valueOf(earth.planetMass));
TextView planetGravityValue = (TextView)findViewById(R.id.dataView3);
planetGravityValue.setText(String.valueOf(earth.planetGravity));
TextView planetColoniesValue = (TextView)findViewById(R.id.dataView4);
planetColoniesValue.setText(String.valueOf(earth.planetColonies));
TextView planetPopulationValue = (TextView)findViewById(R.id.dataView5);
planetPopulationValue.setText(String.valueOf(earth.planetPopulation));
TextView planetMilitaryValue = (TextView)findViewById(R.id.dataView6);
planetMilitaryValue.setText(String.valueOf(earth.planetMilitary));
TextView planetBaseValue = (TextView)findViewById(R.id.dataView7);
planetBaseValue.setText(String.valueOf(earth.planetBases));
TextView planetForceFieldValue = (TextView)findViewById(R.id.dataView8);
planetForceFieldValue.setText(String.valueOf(earth.planetProtection));
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) { // the error is here
return true;
}
return super.onOptionsItemSelected(item);
}
}
Most likely your R.menu.main xml file does not contain an item having #+id/action_settings as its id. Check your R.menu.main xml file ans make sure the action_settings id is set.
As say Quanturium this mean you don't have an item with this name. But as you are talking about "action_setting" you're in fact talking about special item which are not commonly in the XML main file.
Note: I'm not a "pro" in Android, so I just hope this will help.
Have a look at the folder on the left of Android Studio. You have one named "res". Inside you have drawable, values etc... Do you have one named "menu"?
If not create one: clic right on "res", select "New / Android ressource directory" and give "menu" as name.
Now we have a folder which will contain the data for our menu, like action_settings etc...
Now, clic right on this new folder and select "New / Menu ressource file".
The name you'll give must be the name of the activity.
Eg you have a Java piece of code named "Creation", the activity (in the layout folder) is named "activity_creation.xml", so in the menu folder you have to give "creation" as name of the file, which will be created as "creation.xml".
Now, in this file you have to write:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="net.XXX.YYY.ZZZZ" >
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
where XXXX and YYYY are the directory of your app (same as yu write in top of yur Java code), and ZZZZ is the name of the activity (so in my example "creation")
As know you have a "menu", and an action_settings, in your code the following lines will be OK:
#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);
return true;
}
//--------------------------------------------------------------------------------
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Understanding the goal of each folder in Android is a bit hard but necessary as a lot of "smalls problems" came from that.

Creating a basic Android Project now adds a Fragment Layout?

This is weird. I had recently gotten into Android programming. I made a fresh install but when I create a new project there is this new option called Fragment Layout Name at the very end of the page where you specify your Activity name. I haven't had this happen before but when I open my main activity this is what I get. Also half of it is filled with errors according to Android. Is there anyway I can go back and avoid this?
package com.example.quizactivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Do as follows, this works for me..
Step-1:
Right Click on your Project -> Properties -> Android -> In Library panel, remove appcompat_v7 library, Apply and Ok
Step-2:
In Project goto res -> values -> style.xml
In line <style name="AppBaseTheme" parent="Theme.AppCompat.Light"> change parent value from Theme.AppCompat.Light to android:Theme.Light
Step-3:
In Project goto res -> values-v11 -> style.xml
In line <style name="AppBaseTheme" parent="Theme.AppCompat.Light"> change parent value from Theme.AppCompat.Light to android:Theme.Holo.Light
Step-4:
In Project goto res -> values-v14 -> style.xml
In line <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar"> change parent value from Theme.AppCompat.Light.DarkActionBar to android:Theme.Holo.Light.DarkActionBar
Step-5:
In Project goto menu -> main.xml remove these lines in menu tag:
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.test.MainActivity"
and in item tag change this line from app:showAsAction="never" to android:showAsAction="never"
In project, goto res -> layout -> delete fragment.xml
Step-6:
In MainActivity extends Activity not ActionBarActivity and finally your MainActivity.java after remove unnecessary code, looks like this:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
return true;
}
}
Enjoy:)
When creating a new project Select Minimum SDK version as upper or higher as u can . and then u will get rid of app compact .
I have chosen Miminum SDK 4.0 and get rid of it .

Firing an event when clicking a menu in Android

I have a basic project and question. My start-up code is MainActivity.java, and menu belonging to it is res/menu/main.xml. Here is the content of it:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_add"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/menu_add_planet"/>
<item
android:id="#+id/menu_config"
android:orderInCategory="105"
android:showAsAction="never"
android:title="#string/menu_config_planet"/>
When user clicks (or taps) on the add planet option on the menu, and I want the class to be activated.That class is NewPlanet.java Here is the content of it:
import android.app.Activity;
import android.os.Bundle;
public class NewPlanet extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
}
}
I anticipate that there must be a binding between the item element in the res/menu/main.xml and newPlanet but how?
Thanks in advance.
In your activity from where user will click the add planet option have the following:
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch(item.getItemId()) {
case R.id.menu_add:
intent = new Intent(this, NewPlanet.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.startActivity(intent);
break;
}
return true;
}
Make sure you have the Action bar. You can show it by having getActionBar().show(); in onCreate(). Also make sure you are not having both title bar and action bar at the same time.

Categories

Resources