Android Up button quitting application instead of going to parent - java

So in my app, when I press the up button, the activity quits instead of going to its parent Activity. What might be wrong here?
SettingsActivity.java:
public class SettingsActivity extends AppCompatPreferenceActivity {
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
LinearLayout content = (LinearLayout) root.getChildAt(0);
LinearLayout toolbarContainer = (LinearLayout) View.inflate(this, R.layout.activity_settings, null);
root.removeAllViews();
toolbarContainer.addView(content);
root.addView(toolbarContainer);
mToolbar = (Toolbar) toolbarContainer.findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
addPreferencesFromResource(R.xml.pref_general);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
NavUtils.navigateUpFromSameTask(this);
}
}
How this activity is called:
private void openSettingsActivity() {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
}
And the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pt.bluecover.wearable3d"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="23" />
<android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/female_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".DrawerActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings"
android:parentActivityName=".DrawerActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="pt.bluecover.wearable3d.DrawerActivity" />
</activity>
</application>
</manifest>
So, What might be wrong with this behavior?

Add this in your SettingsActivity
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(menuItem);
}
Don't forget to override onBackPressed and call super.onBackPressed();
#Override
public void onBackPressed() {
super.onBackPressed();
}

try this code
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
//NavUtils.navigateUpFromSameTask(this);
finish();
}

Related

How to sync with time in custom calendar that I have made.? Like when I open my calendar it should show the current date and month

Main Activity ScreenI have made a custom calendar with textview, So I want the calendar to show current date and month when I open the calendar...
`My calendar should open directly in the current month and show the current date, just like google calendar.
<TextView
android:textColor="#color/Blue"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:fontFamily="#font/caviardreams"
android:gravity="top|center"
android:text="1"
android:textSize="11sp"
android:textStyle="bold"
android:maxWidth="1dp"
android:maxHeight="1dp"/>
<TextView
android:textColor="#color/Blue"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:fontFamily="#font/caviardreams"
android:gravity="top|center"
android:text="2"
android:textSize="11sp"
android:textStyle="bold"
android:maxWidth="1dp"
android:maxHeight="1dp"/>
<TextView
android:textColor="#color/Blue"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:fontFamily="#font/caviardreams"
android:gravity="top|center"
android:text="3"
android:textSize="11sp"
android:textStyle="bold"
android:maxWidth="1dp"
android:maxHeight="1dp"/>
`
I expect the current date to be highlighted in the current month.
This is the java code of MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager viewPager;
EditText txt;
Button btn;
String str;
AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
//admob app id
MobileAds.initialize(this,"ca-app-pub-6376378742627184~5911477780");
adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
adView.loadAd(adRequest);
}
public void date(View view) {
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return Frag1.newInstance("Frag1, Instance 1");
case 1: return Frag2.newInstance("Frag2, Instance 2");
case 2: return Frag3.newInstance("Frag3, Instance 3");
case 3: return Frag4.newInstance("Frag4, Instance 4");
case 4: return Frag5.newInstance("Frag5, Instance 5");
case 5: return Frag6.newInstance("Frag6, Instance 6");
case 6: return Frag7.newInstance("Frag7, Instance 7");
case 7: return Frag8.newInstance("Frag8, Instance 8");
case 8: return Frag9.newInstance("Frag9, Instance 9");
case 9: return Frag10.newInstance("Frag10, Instance 10");
case 10: return Frag11.newInstance("Frag11, Instance 11");
case 11: return Frag12.newInstance("Frag12, Instance 12");
default: return Frag1.newInstance("Frag1, Default");
}
}
#Override
public int getCount() {
return 12;
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
System.exit(0);
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
finish();
System.exit(0);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
ApplicationInfo app = getApplicationContext().getApplicationInfo();
String filePath = app.sourceDir;
int id = item.getItemId();
if (id == R.id.home)
{
// Handle the camera action
Intent a = new Intent(MainActivity.this,MainActivity.class);
startActivity(a);
}
else if (id == R.id.about)
{
Intent b = new Intent(MainActivity.this,About.class);
startActivity(b);
}
else if (id == R.id.nav_share)
{
Intent c = new Intent(Intent.ACTION_SEND);
c.setType("*/*");
String shareBody = "https://play.google.com/store/apps/details?id=com.jangphong.hem.karbicalender2";
String shareSub = "Download Karbi calendar 2019";
c.putExtra(Intent.EXTRA_SUBJECT,shareSub);
c.putExtra(Intent.EXTRA_TEXT,shareBody);
c.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(new File(filePath)));
startActivity(Intent.createChooser(c,"Share using"));
}
else if (id == R.id.feedback)
{
Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.karbidigitalresources.tk"));
startActivity(in);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jangphong.hem.karbicalender2">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_karbi_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_karbi_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".About" />
<activity
android:name=".SplashScreen"
android:noHistory="true"
android:theme="#style/AppTheme.Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".edit_text" />
<activity android:name=".feb" />
<activity android:name=".march" />
<activity android:name=".april" />
<activity android:name=".may" />
<activity android:name=".june" />
<activity android:name=".july" />
<activity android:name=".august" />
<activity android:name=".sep" />
<activity android:name=".oct" />
<activity android:name=".nov" />
<activity android:name=".dec"></activity>
</application>

Context for onOptionsItemSelected in app-wide menu

This app has just two activities. MainActivity was renamed to SpecialsActivity. The other activity is PizzaActivity. Using the BottomNavigationView, I want to navigate between the two activities. So far, the app opens in SpecialsActivity, and the pizza button does open the PizzaActivity. But then it will not switch back to the SpecialsActivity. I think the issue is related to context. Please help.
SpecialsActivity.java
public class SpecialsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_specials);
Toolbar myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_specials:
Intent specials_intent = new Intent(this, SpecialsActivity.class);
startActivity(specials_intent);
return true;
case R.id.action_pizza:
Intent pizza_intent = new Intent(getApplicationContext(), PizzaActivity.class);
startActivity(pizza_intent);
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
}
activity_specials.xml
<android.support.design.widget.BottomNavigationView
android:layout_width="0dp"
android:layout_height="49dp"
app:itemBackground="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_menu" />
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/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".SpecialsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PizzaActivity"></activity>
</application>
bottom_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_specials"
android:icon="#drawable/ic_home_black_24dp"
android:title="Specials"
app:showAsAction="always"
android:onClick="onOptionsItemSelected" />
<item
android:id="#+id/action_pizza"
android:enabled="true"
android:icon="#drawable/ic_local_pizza_black_24dp"
android:title="Pizza"
app:showAsAction="always"
android:onClick="onOptionsItemSelected"/>
</menu>
Try changing
Intent pizza_intent = new Intent(getApplicationContext(), PizzaActivity.class);
into this
Intent pizza_intent = new Intent(this, PizzaActivity.class);

Run Time Main Activity not come after Splash Activity and app close

Everything in my code looks good in both the .java and .xml files (according to the software) because I have no errors yet every time I click the app icon in the emulator, it brings up the splash screen then the app exits without showing my main activity. Here's my code so far:
SplashActivity.java
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//hide title bar of activity
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//Making activity full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
int t =3000; //time for spash screen 3000 means 3sec
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
}
},t);
}
}
SplashActivity.xml
<ImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:src="#drawable/icon"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
MainActivity.java:
public class MainActivity extends AppCompatActivity
{
String webAdress ="https://www.google.com/";
WebView webView;
FrameLayout frameLayout;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = (WebView) findViewById(R.id.webView);
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView.setWebViewClient(new HelpClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(newProgress);
setTitle("Loading..."); //when url is loading set this on actionbar
if (newProgress == 100) {
frameLayout.setVisibility(View.GONE); // Hide progress bar when page is loaded
setTitle(view.getTitle()); //get amd set title of opend page
}
super.onProgressChanged(view, newProgress);
}
});
webView.getSettings().setJavaScriptEnabled(true); //enable javaScript
//check internet connection
if (haveNetworkConnection()) {
webView.loadUrl(webAdress);
} else {
Toast.makeText(this, "No internet Connection", Toast.LENGTH_SHORT).show();
}
progressBar.setProgress(0);
}
private class HelpClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(View.VISIBLE);
return true;
}
}
private boolean haveNetworkConnection(){
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
for(NetworkInfo ni : networkInfos){
if(ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if(ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//check if the event was the back button and if there's history
if ((keyCode==KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
webView.goBack();
return true;
}
//if it was the back or there is no web page history, bubble up to the default system behaviour
return super.onKeyDown(keyCode, event);
}
}
MainActivity.xml:
<!--Progressbar-->
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="3dip"
android:background="#android:color/transparent">
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="match_parent"
style="?android:attr/progressBarStyleHorizontal"
android:layout_height="7dp"
android:layout_gravity="top"
android:layout_marginTop="-3dp"
android:progressDrawable="#drawable/custom_progress"
android:background="#android:color/transparent"
android:progress="20"/>
</FrameLayout>
<!--WebView-->
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
</WebView>
Here's my manifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!--internet permision-->
<uses-permission android:name="android.permission.INTERNET"/>
<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=".SplashActivity"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity">
</activity>
</application>
Any hints would be greatly appreciated, thank you!
The problem is in onCreate method of MainActivity, you do not provide any UI (xml layout file), as a result, the app cannot find view elements to init, set listeners, etc. I guess you can find an exception in logcat when your app close.
Solution: Provide a layout xml file for MainActivity
public class MainActivity extends AppCompatActivity {
String webAdress ="https://www.google.com/";
WebView webView;
FrameLayout frameLayout;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Add this line
webView = (WebView) findViewById(R.id.webView);
...
}
}
try use
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
Your code is not so good. If you want to show splashscreen only when app start I recommend using the following code:
AndroidManifest.xml
<activity android:name=".view_layer.activities.SplashScreenActivity"
android:theme="#style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
styles.xml
<style name="SplashTheme" parent="#android:style/Theme.NoTitleBar.Fullscreen">
<item name="android:windowBackground">#drawable/splash</item>
</style>
SplashscreenActivity.java
public class SplashscreenActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
More: https://android.jlelse.eu/the-complete-android-splash-screen-guide-c7db82bce565

Select Item on Spinner

I want to ask for help.
I already created a list of activities in Android Studio.
Each Activity contains a specific item. Those items are different "Departments" in our University.
Example:
Activity 1 = College of Computer Studies;
Activity 2 = College of Teacher Education;
Activity 3 = College of Engineering.
My Spinner contains the departments.
My problem is, if I choose "College in Computer Science" in Spinner and click the "SEND" button, I want Activity 1 to be shown.
Would you help me with the code to do that?
**Spinner in activity_main.xml
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spin"
android:entries="#array/punpDepartments"
android:layout_gravity="center_vertical">
</Spinner>
**These are the items in strings.xml
<string-array name="punpDepartments">
<item>College of Computer Studies</item>
<item>College of Business Education</item>
<item>College of Criminal Justice Education</item>
<item>College of Marine Education</item>
<item>College of Nursing</item>
<item>College of Pharmacy</item>
<item>College of Education</item>
**My code in Intent at MainActivity.java
public class MainActivity extends ActionBarActivity {
private static Button button_send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OnClickButtonListener();
}
public void OnClickButtonListener(){
button_send = (Button) findViewById(R.id.button);
button_send.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
Intent intent = new Intent("com.example.imelda.mythesis.ListActivity");
startActivity(intent);
}
}
);
}
**Extends in ListActivity.java
public class ListActivity extends ActionBarActivity {
private static Button button_next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
OnClickButtonListener();
}
#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_list, menu);
return true;
}
public void OnClickButtonListener() {
button_next = (Button) findViewById(R.id.button4);
button_next.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.example.imelda.mythesis.SecondList");
startActivity(intent);
}
}
);
}
**I have also added this in AndroidManifest.xml enter code here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.imelda.mythesis" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
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=".ListActivity"
android:label="#string/title_activity_list" >
<intent-filter>
<action android:name="com.example.imelda.mythesis.ListActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
first get your spinner in the main class like this
Spinner spin =(Spinner)findViewById(R.id.spin);
now in your on click method do this
int position =spin.getSelectedItemPosition();
//change the activities with yours
switch (position){
case 0: intent.setClass(Activity1.class,MainActivity.this);
break;
case 1: intent.setClass(Activity2.class,MainActivity.this);
break;
case 2: intent.setClass(Activity3.class,MainActivity.this);
break;
case 3: intent.setClass(Activity4.class,MainActivity.this);
break;
case 4: intent.setClass(Activity5.class,MainActivity.this);
break;
}
startActivity(intent);

icon not displayed on actionbar

I was going through the tutorial by google and couldn't figure out how to place search icon on action bar.
this is the main_activity_actions.xml code :-
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:orderInCategory="100"
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>
this is the MainActivity.java :-
public class MainActivity extends ActionBarActivity
{
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
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;
}
}
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
public void openSearch()
{
}
public void openSettings()
{
}
}
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:theme="#style/Theme.AppCompat.Light"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.example.myfirstapp.MainActivity"
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.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
</manifest>
I have already seen few answers and posted an the stack overflow and tried them and it still doesn't work
the search icon never shows up while I try to run it
can someone suggest what to do?
in activity_action.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:(YOUR_PROJECT_NAME)="http://schemas.android.com/apk/res-auto"
>
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
YOUR_PROJECT_NAME:showAsAction="always" />

Categories