I'm just following another tutorial but the result is different. When I'm trying to run my apk, menu icon won't show up on primary layout (activity_main.xml) Anyone knows what I missed?
menu_main_activity.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">
<!-- NEW NOTE -->
<item
android:id="#+id/action_create"
android:enabled="true"
android:icon="#android:drawable/ic_menu_add"
android:orderInCategory="0"
android:title="create"
android:visible="true"
app:showAsAction="always" />
<!-- SETTINGS -->
<item
android:id="#+id/action_settings"
android:enabled="true"
android:icon="#android:drawable/ic_menu_manage"
android:orderInCategory="10"
android:title="settings"
android:visible="true"
app:showAsAction="ifRoom" />
</menu>
MainNote.java:
package com.example.lenovo.home;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import android.view.View.OnClickListener;
public class MainNote extends AppCompatActivity {
private ListView mListNotes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_note);
mListNotes = (ListView) findViewById(R.id.main_listview);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_activity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create: //run NoteActivity in new note mode
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_settings:
//TODO show settings activity
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
//load saved notes into the listview
//first, reset the listview
mListNotes.setAdapter(null);
ArrayList<Note> notes = Utilities.getAllSavedNotes(getApplicationContext());
//sort notes from new to old
Collections.sort(notes, new Comparator<Note>() {
#Override
public int compare(Note lhs, Note rhs) {
if (lhs.getDateTime() > rhs.getDateTime()) {
return -1;
} else {
return 1;
}
}
});
if (notes != null && notes.size() > 0) { //check if we have any notes!
final NoteAdapter na = new NoteAdapter(this, R.layout.view_note_item, notes);
mListNotes.setAdapter(na);
//set click listener for items in the list, by clicking each item the note should be loaded into NoteActivity
mListNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//run the NoteActivity in view/edit mode
String fileName = ((Note) mListNotes.getItemAtPosition(position)).getDateTime()
+ Utilities.FILE_EXTENSION;
Intent viewNoteIntent = new Intent(getApplicationContext(), NoteActivity.class);
viewNoteIntent.putExtra(Utilities.EXTRAS_NOTE_FILENAME, fileName);
startActivity(viewNoteIntent);
}
});
} else { //remind user that we have no notes!
Toast.makeText(getApplicationContext(), "you have no saved notes!\ncreate some new notes :)"
, Toast.LENGTH_SHORT).show();
}
}
}
And, the last is my activity_main_note.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.lenovo.home.MainNote">
<ListView
android:id="#+id/main_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible" />
</LinearLayout>
UPDATE
This is my styles code
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
This is my theme code for application.
I have just run your code and it works fine.
I am running it with the following theme in styles.xml:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
</resources>
In manifest I have android:theme="#style/AppTheme" in the application tag.
And my Activity extends AppCompatActivity
Also check you have put the menu xml in res/menu folder.
The only thing I see but it is regarding the item being selected is that the return statement is wrong, but it doesn't have to do with the icons not appearing.
In onOptionsItemSelected(MenuItem item) you should return true if you handle the request or false if not.
Change it like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean rtn = false;
switch (item.getItemId()) {
case R.id.action_create: //run NoteActivity in new note mode
startActivity(new Intent(this, NoteActivity.class));
rtn = true;
break;
case R.id.action_settings:
//TODO show settings activity
rtn = true;
break;
default:
rtn = super.onOptionsItemSelected(item);
}
return rtn;
}
See this question: Should "android: onOptionsItemSelected" return true or false
EDIT I
I see in your styles.xml you are extending Theme.AppCompat.Light.NoActionBar, which doesn't have an ActionBar.
In this case you can switch to a theme with an ActionBar as I am using or otherwise you need to add your own action bar to the layout using a Toolbar.
Related
Currently, I am attempting to creating a popup menu on an ImageButton which works, though I want the size (width) of the menu to be smaller as well to inline them side by side? But that is not the main issue it is the size(width) I would like to reduce either for a png or just the word itself. I'm hoping you guys could help me figure this out. I just spent 3days figuring out the menu. Also, I have tried adding some padding and the android: width/android:layout_width. None of these have worked and I'm hoping there is a way around this issue.
Main.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class MainActivity extends AppCompatActivity
{
public WebView webView;
public EditText search_bar;
private ImageButton options_menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
//Open in Equinox instead of Deafult Browser
webView.setWebViewClient(new
WebViewClient());
//WebView - JavaScript-WebViewSettings-HomePage
final WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.loadUrl("https://www.Google.ca");
//OptionsBtn
options_menu = (ImageButton) findViewById(R.id.options_menu);
options_menu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, options_menu);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.back:
if(webView.canGoBack()){
webView.goBack();
}
else{
webView.reload();
}
return true;
case R.id.forward:
if(webView.canGoForward()){
webView.goForward();
}
else{
webView.reload();
}
return true;
case R.id.refresh:
webView.reload();
default:
return false;
}
}
});
popup.show(); //showing popup menu
}
}); //closing the setOnClickListener method
//"Go" on Keyboard with search
search_bar=(EditText)findViewById(R.id.search_bar);
search_bar.setOnEditorActionListener(new OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
if(arg1 == EditorInfo.IME_ACTION_GO)
{
if (search_bar.getText().toString().contains(".com")) {
webView.loadUrl("https://".concat(search_bar.getText().toString()));
} else {
webView.loadUrl("https://www.google.ca/search?q=".concat(search_bar.getText().toString()));
}
}
return false;
}
});
}
public void onBackPressed(){
if (true){
webView.goBack();
}
else{
webView.reload();
}
}
}
popup_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/back"
android:title="#string/back" />
<item
android:id="#+id/forward"
android:title="#string/forward" />
<item
android:id="#+id/refresh"
android:title="#string/refresh" />
I can reduce the height and text size of the menu items with the help of below codes:
res/values/styles.xml:
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:dropDownListViewStyle">#style/PopupMenuListView</item>
<item name="android:actionBarWidgetTheme">#style/PopupMenuTextView</item>
<item name="android:popupMenuStyle">#style/PopupMenu</item>
<!-- Change Overflow Menu ListView Item Height & Property -->
<item name="android:listPreferredItemHeightSmall">10dp</item>
<item name="android:listPreferredItemPaddingLeft">5dp</item>
<item name="android:listPreferredItemPaddingRight">5dp</item>
</style>
<!-- Change Overflow Menu ListView Divider Property -->
<style name="PopupMenuListView" parent="#android:style/Widget.Holo.ListView.DropDown">
<item name="android:divider">#FF0000</item>
<item name="android:dividerHeight">2dp</item>
</style>
<!-- Change Overflow Menu ListView Text Size and Text Size -->
<style name="PopupMenuTextView" parent="#style/android:Theme.Holo.Light">
<item name="android:textColor">#00FF00</item>
<item name="android:textSize">5sp</item>
</style>
<!-- Change Overflow Menu Background -->
<style name="PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
<item name="android:popupBackground">#888888</item>
</style>
</resources>
Add the above codes in styles.xml(v11) and styles.xml(v14).
For More Detail:
Refer Action Bar Overflow Menu Customization
I get the error "Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set WindowActionBar to false in your theme to use a toolbar instead" whenever I try to run my app in the emulator on Android Studio and it crashes upon startup. I understand that this question has been asked before, but when I remove the extends AppCompatActivity as I am told to do in other posts it then gives me an error for the setSupportActionBar(toolbar) line a bit further down in the code.
As far as I understand this is an error with Android Studio getting confused about the native toolbar and the toolbar that I'm trying to implement. Perhaps I'm misunderstanding the crux of the problem? Why is it giving me an error for setSupportActionBar(toolbar) once I get rid of the extends statement?
The main activity is using the "AppTheme"
Thanks.
MainActivity Code for reference:
package com.treehouse.android.movies;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
//extends AppCompatActivity
public class MainActivity extends AppCompatActivity
{
static public ArrayList<Movie> moviesList;
static public ArrayList<String> images;
public String mostPopular="http://api.themoviedb.org/3/movie/popular?api_key=";
public String highRated="http://api.themoviedb.org/3/movie/top_rated?api_key=";
//Make both GridAdapter and GridView non-Static?
static public GridAdapter gridAdapter;
static public GridView gridView;
public static boolean connectionEnabled;
public Context currentContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String result="";
moviesList=new ArrayList<>();
images=new ArrayList<>();
currentContext=getApplicationContext();
if (isNetworkAvailable()!= false) {
connectionEnabled=true;
getJsonData(0);
new GetMovies(currentContext);
gridView =(GridView) findViewById(R.id.moviesGridView);
gridAdapter =new GridAdapter(MainActivity.this,moviesList,images);
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent movieIntent=new Intent(getApplicationContext(),DetailsActivity.class);
Log.i("Default position ", String.valueOf(position));
movieIntent.putExtra("position",position);
startActivity(movieIntent);
}
});
}
else{
Toast.makeText(this, "Network Is Not Available", Toast.LENGTH_LONG).show();
connectionEnabled=false;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
//get json file
//0 for most popular
//1 for highest-rated
public void getJsonData(int searchBy){
GetMovies downloadTask=new GetMovies(currentContext);
try {
if (searchBy == 0 ){
downloadTask.execute(mostPopular);
}
else if(searchBy == 1){
downloadTask.execute(highRated);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#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.mostpopular_button) {
if (isNetworkAvailable()!= false) {
new GetMovies(currentContext).execute(mostPopular);
gridAdapter.notifyDataSetChanged();
}
else{
Toast.makeText(this, "Network Is Not Available", Toast.LENGTH_LONG).show();
}
}
else if (id== R.id.highrated_button){
if (isNetworkAvailable()!= false) {
new GetMovies(currentContext).execute(highRated);
gridAdapter.notifyDataSetChanged();
}
else{
Toast.makeText(this, "Network Is Not Available", Toast.LENGTH_LONG).show();
}
}
return super.onOptionsItemSelected(item);
}
}
Styles Code for reference:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
Manifest Code for reference:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.treehouse.android.movies" >
<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" part of application -->
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN"
android:theme="#style/AppTheme"
/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
change your style.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
replace to this :
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowActionBar">true</item>
<item name="windowNoTitle">true</item>
</style>
Since your Activity's theme is set to AppTheme, it comes with an "action bar" by default. When you then call setSupportActionBar(toolbar), your app crashes because you've already got an actionbar (from your theme).
Simply change your Activity's theme to AppTheme.NoActionBar in your manifest.
I am trying to change the theme or color of the app when the user selects an option from an AlertDialog. I made the same technique for changing the size of font, and it's works fine. I don't what is the mistake I made for changing the color.
strings.xml:
<resources>
<string-array name="font_sizes">
<item>14</item>
<item>16</item>
<item>18</item>
<item>20</item>
<item>22</item>
</string-array>
<string-array name="app_colors">
<item>0</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
</string-array>
</resources>
styles.xml:
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#color/colorPrimaryDark</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="BlackTheme">
<item name="colorPrimary">#FF000000</item>
<item name="colorPrimaryDark">#FF000000</item>
<item name="colorAccent">#FF000000</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#FF000000</item>
</style>
<style name="BlueTheme">
<item name="colorPrimary">#FF0000FF</item>
<item name="colorPrimaryDark">#FF0000FF</item>
<item name="colorAccent">#FF0000FF</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#FF0000FF</item>
</style>
<style name="GreenTheme">
<item name="colorPrimary">#008000</item>
<item name="colorPrimaryDark">#008000</item>
<item name="colorAccent">#008000</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#008000</item>
</style>
<style name="MagentaTheme">
<item name="colorPrimary">#D500F9</item>
<item name="colorPrimaryDark">#D500F9</item>
<item name="colorAccent">#D500F9</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#D500F9</item>
</style>
</resources>
PreferencesActivity.java:
package sa.edu.qu.coc.cocapps.prefs;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import sa.edu.qu.coc.cocapps.R;
public class PreferencesActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar toolbar = null;
public static final String PREFS_KEY = "preferences";
private static int item = 0, color = 0;
private LinearLayout fontSize;
private LinearLayout appColor;
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
initViews();
setSupportActionBar(toolbar);
fontSize.setOnClickListener(this);
appColor.setOnClickListener(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void initViews() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
fontSize = (LinearLayout) findViewById(R.id.fontSize);
appColor = (LinearLayout) findViewById(R.id.appColor);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fontSize:
AlertDialog.Builder changeFontSizeDialog = new AlertDialog.Builder(this)
.setTitle("Select Size")
.setIcon(android.R.drawable.sym_action_chat)
.setSingleChoiceItems(R.array.font_sizes, item, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
editor = prefs.edit();
editor.putInt("fontSize", i);
editor.commit();
item = i;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// DO not do anything.
}
});
changeFontSizeDialog.show();
break;
case R.id.appColor:
AlertDialog.Builder changeAppColorDialog = new AlertDialog.Builder(this)
.setTitle("Select color")
.setIcon(android.R.drawable.sym_action_chat)
.setSingleChoiceItems(R.array.app_colors, color, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
editor = prefs.edit();
editor.putInt("appColor", which);
editor.commit();
color = which;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// DO not do anything.
}
});
changeAppColorDialog.show();
break;
}
}
#Override
protected void onStart() {
super.onStart();
switch(prefs.getInt("appColor", 0))
{
case 0:
this.setTheme(R.style.AppTheme);
return;
case 1:
this.setTheme(R.style.BlackTheme);
return;
case 2:
this.setTheme(R.style.BlueTheme);
return;
case 3:
this.setTheme(R.style.GreenTheme);
return;
case 4:
this.setTheme(R.style.MagentaTheme);
return;
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Because themes don't change like that. A theme has to be set before inflating the views. Afterwards, the views will not be refreshed to a new theme. However if you were to create a new View it would pick up the new theme.
Create a base Activity for your app and override onCreate to set the theme. Derive all your other activities from this base Activity.
You can also check this particular tutorial (if you are doing activity theme):
http://mrbool.com/how-to-change-the-layout-theme-of-an-android-application/25837
I solved it. The following code is the whole solution.
strings.xml:
<resources>
<string-array name="font_sizes">
<item>14</item>
<item>16</item>
<item>18</item>
<item>20</item>
<item>22</item>
</string-array>
<string-array name="app_colors">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</string-array>
</resources>
styles.xml: (Also, do not forget to add the same custom styles to styles.xml (v21)):
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#color/colorPrimaryDark</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="BlackTheme">
<item name="colorPrimary">#FF000000</item>
<item name="colorPrimaryDark">#FF000000</item>
<item name="colorAccent">#FF000000</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#FF000000</item>
</style>
<style name="BlueTheme">
<item name="colorPrimary">#FF0000FF</item>
<item name="colorPrimaryDark">#FF0000FF</item>
<item name="colorAccent">#FF0000FF</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#FF0000FF</item>
</style>
<style name="GreenTheme">
<item name="colorPrimary">#008000</item>
<item name="colorPrimaryDark">#008000</item>
<item name="colorAccent">#008000</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#008000</item>
</style>
<style name="MagentaTheme">
<item name="colorPrimary">#D500F9</item>
<item name="colorPrimaryDark">#D500F9</item>
<item name="colorAccent">#D500F9</item>
<item name="android:navigationBarColor" tools:targetApi="lollipop">#D500F9</item>
</style>
</resources>
PreferencesActivity.java:
package sa.edu.qu.coc.cocapps.prefs;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import sa.edu.qu.coc.cocapps.R;
public class PreferencesActivity extends AppCompatActivity implements View.OnClickListener {
private Toolbar toolbar = null;
private LinearLayout fontSize, appColor;
public static final String PREFS_KEY = "preferences";
private static int item = 0, color = 0;
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
prefs = getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
switch(prefs.getInt("appColor", 0)) {
case 0:
activity.setTheme(R.style.AppTheme);
break;
case 1:
activity.setTheme(R.style.BlackTheme);
break;
case 2:
activity.setTheme(R.style.BlueTheme);
break;
case 3:
activity.setTheme(R.style.GreenTheme);
break;
case 4:
activity.setTheme(R.style.MagentaTheme);
break;
}
setContentView(R.layout.activity_preferences);
initViews();
setSupportActionBar(toolbar);
fontSize.setOnClickListener(this);
appColor.setOnClickListener(this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void initViews() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
fontSize = (LinearLayout) findViewById(R.id.fontSize);
appColor = (LinearLayout) findViewById(R.id.appColor);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fontSize:
AlertDialog.Builder changeFontSizeDialog = new AlertDialog.Builder(this)
.setTitle("Select Size")
.setIcon(android.R.drawable.sym_action_chat)
.setSingleChoiceItems(R.array.font_sizes, item, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
editor = prefs.edit();
editor.putInt("fontSize", i);
editor.commit();
item = i;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// DO not do anything.
}
});
changeFontSizeDialog.show();
break;
case R.id.appColor:
AlertDialog.Builder changeAppColorDialog = new AlertDialog.Builder(this)
.setTitle("Select Color")
.setIcon(android.R.drawable.sym_action_chat)
.setSingleChoiceItems(R.array.app_colors, color, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
editor = prefs.edit();
editor.putInt("appColor", i);
editor.commit();
color = i;
activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// DO not do anything.
}
});
changeAppColorDialog.show();
break;
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
I'm learning Material Design from video tutorial provided by slidenerd.In that they put one next icon on toolbar,everything is working in that tutorial but when i'm implemented it the icon is not appearing.
Here,i'm attaching my files please have a look and help me out at my learning stage.Please!!!
MainActivity.java
package materialtest.example.ritzipsy.mytoolbar5;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.id_settings) {
Toast.makeText(this, "You have Clicked Setting menu", Toast.LENGTH_SHORT).show();
}
if (id == R.id.id_navigate) {
Toast.makeText(this, "You have Clicked Next menu", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="materialtest.example.ritzipsy.mytoolbar5.MainActivity">
<include android:id="#+id/app_bar"
layout="#layout/app_bar"></include>
</RelativeLayout>
my_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/tools">
<item
android:id="#+id/id_settings"
android:title="Settings"
app:showAsAction="never">></item>
<item
android:id="#+id/id_navigate"
android:icon="#drawable/ic_next_arrow"
android:orderInCategory="200"
android:title="Next"
app:showAsAction="always"></item>
</menu>
app_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.co0m/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary">
</android.support.v7.widget.Toolbar>
style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base">
<!-- Customize your theme here. -->
</style>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
</resources>
Got Output as
Expected output to be
Just change your menu xml as below. The problem is with this line
xmlns:app="http://schemas.android.com/apk/tools"
<?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/id_settings"
android:title="Settings"
app:showAsAction="never"></item>
<item
android:id="#+id/id_navigate"
android:icon="#drawable/ic_next_arrow"
android:orderInCategory="200"
android:title="Next"
app:showAsAction="always"></item>
</menu>
Im following the next tutorial: Adding Action Buttoms, I did it step by step but when I run my app doesn´t shows any icon. I was debugging but everything seems correct and I have any nullPointerException or something like that.
This is my mainActivity:
package com.training.training.appone;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = " com. training.example.appone.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
#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_my, menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activiy_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.txt_edit_message);
String message = editText.getText().toString();
// El primer parametro es el KeyName:
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
And I put this XML:
<?xml version="1.0" encoding="utf-8"?>
<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="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
I have an error in the last line "android:showsAsAction="never", I have the libray downloaded and referenced in my build gradle: compile 'com.android.support:appcompat-v7:22.0.0' I also tryed changed "android" to "res-auto", but it says that the items must have a title (they have them):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/res-auto">
<!-- 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="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
My library:
In this point I have no idea what happends.
Make the following changes in your menu.xml
<menu
....
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
...
app:showAsAction="never" />
</menu>
And if you want to display your menu on actionBar then it should be app:showAsAction="always".
In your XML file, Please change this line
app:showAsAction="always"
instead of
android:showAsAction="never"
Probably as you are using AppCompat library, you should use
app:showAsAction="never"
instead
android:showAsAction="never"
If you look at the xml schemas in the tutorial you have both:
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto"
Notice the xmlns:android and xmlns:yourapp are different. So all you need to do is:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto">
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
yourapp:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
yourapp:showAsAction="never" />
</menu>
The android and yourapp tags can be named however you want. They are just a named reference to the schema.