Hello,
I create that thread to share with you a tutorial showing you how to implement a Navigation Drawer with a Toolbar on Android. You can find the tutorial here on my blog : http://www.ssaurel.com/blog/implement-a-navigation-drawer-with-a-toolbar-on-android-m/ . There are also others great tutorials for Android development.
If you prefer to read the tutorial here, this is the complete content :
Implement a Navigation Drawer with a Toolbar on Android
Navigation drawer is a great UI pattern recommended by Google when you design your Android application. Introduced with Android Lollipop, the Toolbar widget is a flexible way to customize easily the action bar. In this tutorial, you’re going to learn how to implement a navigation drawer with a toolbar on Android M.
1. Get Material Colors
First, you need to get material colors for your application. A website like http://www.materialpalette.com can be useful to create quickly your material colors file. Here, we choose green and light green as primary colors :
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="primary">#4CAF50</color>
<color name="primary_dark">#388E3C</color>
<color name="primary_light">#C8E6C9</color>
<color name="accent">#8BC34A</color>
<color name="primary_text">#212121</color>
<color name="secondary_text">#727272</color>
<color name="icons">#FFFFFF</color>
<color name="divider">#B6B6B6</color>
</resources>
Put your XML resource file, got from Material Palette, in the folder res/values of your Android project.
2. Configure your dependencies
Now, it’s time to configure dependencies in your build.gradle file. You need to import the following libraries :
Code:
com.android.support:appcompat-v7:23.3.0
com.android.support:design:23.3.0
3. Create a No Action Bar theme
To use the Toolbar widget, you need to create a No Action Bar theme for your activity. In your styles.xml file under res/values, you can create the following theme :
Code:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>
</style>
<style name="MyAppTheme" parent="@style/AppTheme" />
</resources>
To enable some specific properties available from API V21, you need to create a folder named values-v21 and override the MyAppTheme like that :
Code:
<resources>
<style name="MyAppTheme" parent="AppTheme">
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
<item name="android:windowSharedElementExitTransition">@android:transition/move</item>
</style>
</resources>
Finally, you need to apply the MyAppTheme to a specific Activity with a Toolbar widget or if you want to your entire application :
Code:
<application
android:theme="@style/MyAppTheme" >
...
</application>
4. Create layout for the Toolbar
The Toolbar widget has been created to play the role that was dedicated to Action Bar previously. It can be used to hold :
Action menu
App title and subtitle
Navigation button(s)
Like the Toolbar will be used between several activities’ layouts, we create a separate layout file and apply our specific configuration with colors for example :
Code:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/primary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
Now, we could include the Toolbar in each activity and have just one place to change its configuration.
5. Add the Navigation Drawer to the Activity
Navigation Drawer is a great UI pattern recommended by Google when you develop Android applications. It’s a great way to organise navigation inside an application. Implementation is easy and we need to use DrawerLayout widget to implement it.
The layout of our main Activity will be like that :
Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/toolbar" />
<!-- For fragments -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frame"/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/nav_items" />
</android.support.v4.widget.DrawerLayout>
Here, you can note that we include the Toolbar widget defined at the step 4.
6. Create a navigation items menu
To define the content of the navigation drawer, we can define a navigation items menu in res/menu :
Code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:id="@+id/refresh"
android:title="@string/refresh"
android:icon="@drawable/ic_action_refresh" />
<item android:id="@+id/stop"
android:title="@string/stop"
android:icon="@drawable/ic_action_stop" />
</group>
</menu>
Here, we define juste two entries in the menu.
7. Configure Toolbar and Navigation Drawer in Activity
All the resources file are ready. So, it’s time to configure Toolbar and Navigation Drawer in the Activity. It’s easy and we use dedicated method named configureToolbar and configureNavigationDrawer :
Code:
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
private RelativeLayout layout;
private DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (RelativeLayout) findViewById(R.id.layout);
configureNavigationDrawer();
configureToolbar();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.empty_menu, menu);
return true;
}
private void configureToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setHomeAsUpIndicator(R.drawable.ic_action_menu_white);
actionbar.setDisplayHomeAsUpEnabled(true);
}
private void configureNavigationDrawer() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navView = (NavigationView) findViewById(R.id.navigation);
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment f = null;
int itemId = menuItem.getItemId();
if (itemId == R.id.refresh) {
f = new RefreshFragment();
} else if (itemId == R.id.stop) {
f = new StopFragment();
}
if (f != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, f);
transaction.commit();
drawerLayout.closeDrawers();
return true;
}
return false;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch(itemId) {
// Android home
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
// manage other entries if you have it ...
}
return true;
}
}
As you can see, it’s really simple to assemble all the pieces of the puzzle to have a functional application with a Navigation Drawer and a Toolbar.
If you have some questions about the content of fragments used here, it’s really simple. For example, this is the content of the RefreshFragment :
Code:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.refresh_fragment_layout, container, false);
return v;
}
}
After that, it’s your job to complete the fragment with your content.
8. Demo
Now, it’s time for demo of the application created. Some screenshots :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
9. Bonus
In bonus, you can follow this tutorial in a live coding video available in two parts on Youtube :
Don't hesitate to give it a try and give me your feedbacks.
I hope it can help you .
Sylvain
sylsau said:
Hello,
I create that thread to share with you a tutorial ...
...
Don't hesitate to give it a try and give me your feedbacks.
I hope it can help you .
Sylvain
Click to expand...
Click to collapse
Thanks for tutorial. Can you share the code? Thanks
Related
hey everyone
im having a lil bit of trouble here and im hoping someone will have the knowledge i need...im using eclipse trying to build an app. i have a real simple app inmind and it consists of 4 icons that will link to their own forum, but im stuck trying to figure out how to link these websites when clicked...that being said im fairly new to the java world and im just looking for a nudge in the right direction here on where/how to make these buttons work.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
[/URL] Uploaded with ImageShack.us[/IMG]
Android uses a Uri scheme to access resources outside the scope of your program. Checkout the Uri class and the startActivity method in the Context class.
As far as what the uri needs to contain, it is very simple, just the website address you want to go to. Here is the uris needed to access google services
http://developer.android.com/guide/appendix/g-app-intents.html
From something awesome
thanks for your advice.i really wish i knew more about java; i take it all my changes will be in my java & manifest files?? i dont know what actions to take really and i need a lil bit more indepth answer on exactly what i need to add/change...
this example assumes you used an xml layout file called http_button_layout.xml and has a button inside called button1
Code:
/**
* Created by IntelliJ IDEA.
* User: Tyler
* Date: 5/10/11
* Time: 6:47 PM
*/
public class HTTPClickButton extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
//call the parents onCreate
super.onCreate(savedInstanceState);
//set the view to some xml layout file with a button in it
setContentView(R.layout.http_button_layout);
//get an instance of that button to be used in the code
Button launchWebPage = (Button)findViewById(R.id.button1);
//attach an onClickListener to the button and define its action
launchWebPage.setOnClickListener(new View.OnClickListener() {
//the action to partake upon pressage of said button
public void onClick(View view) {
//the Uri.parse() method takes a string and converts it to a uri that android knows what to do with.
//in this case it sees a link and launches the web browser
//changing Intent.ACTION_VIEW will change the behavior of the link
//Intent.ACTION_WEB_SEARCH is the other option
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse("http://www.fistfulofneurons.com/") ));
}
});
}
}
hope this helps. of course this is one button but it will work for more. just rinse and repeat
to answer that i haven't made an xml layout file yet called http_button_layout.xml but i take it i will have to make an xlm layout file and java class for each icon? sorry supernewb when it comes to this code stuff, almost like learning a new language,lol...
you dont have to. but you will have to perform the .setOnClickListener() on each button.
are you using the Button class or is it just an image or someother class? cause it doesnt matter if it is a Button or not. even if its a TextView you can still perform the .setOnClickListener() i believe it is a function defined in the View abstract class.
im using an imagebutton option, fyi....dont know how much that changes things here tho...
You are golden. Since you are using java as the layout you just need to perform the setOnClickListener() on a reference of your ImageButton and forget anything i said about xml. Although you should investigate xml for layouts as its alot easier and faster to make a layout
You mind posting what you have so far to generate that screen grab up top?
From something awesome
HTML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/xlapps"
>
<ImageButton
android:id="@+id/imageButton1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
<ImageButton
android:id="@+id/imageButton2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
<ImageButton
android:id="@+id/imageButton3"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
<ImageButton
android:id="@+id/imageButton4"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/xlnet"
></ImageButton>
</LinearLayout>
this is my main xml if this answers your question about the screen grab? rightnow i only have my main app icon, i need to get my 4 other icons inserted but other than that this parsing is my only hurdle, really..
lol now im confused, so does that mean i only need to do this part of your code in java, and does that mean i don't have to make a button_layout.xml? lol sorry java's not my first langauge, they totally should of taught this in school
Code:
//attach an onClickListener to the button and define its action
launchWebPage.setOnClickListener(new View.OnClickListener() {
//the action to partake upon pressage of said button
public void onClick(View view) {
//the Uri.parse() method takes a string and converts it to a uri that android knows what to do with.
//in this case it sees a link and launches the web browser
//changing Intent.ACTION_VIEW will change the behavior of the link
//Intent.ACTION_WEB_SEARCH is the other option
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse("http://www.fistfulofneurons.com/") ));
}
});
K so you are using an xml layout. Is that called main.xml? In my example you would replace my R.layout.http_button_layout with R.layout.main
And then when referencing the buttons you would change my R.id.button1 to the @+id of each button in your layout. So it would be R.id.imagebutton1.
The R class is a class generated at compile time to help reference ui elements defined in xml from your java code
And i don't think you can have ids defined in xml with capital letters. So you might want to change imageButton1 to image_button1
From something awesome
awesome yea im using main.xml for the layout.... so all i need to do is set up 1 java class for all the icons and do all your code there?...
well i started a new java class, i just called it buttons, im not sure if thats the right way to do all this but i changed what you said and im getting alot less errors so thats good.lol but heres a look at my buttons.java file. any idea what could be wrong? it showed my imagebutton1 of (R.id.imagebutton1) and image_button1 in the (find view by id) could not be resolved or is not a field...
Code:
package com.frostXLNetwork;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class buttons {
public class HTTPClickButton extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
//call the parents onCreate
super.onCreate(savedInstanceState);
setContentView(R.id.imagebutton1);
Button launchWebPage = (Button)findViewById(R.id.image_button1);
launchWebPage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse("http://xlfx.30.forumer.com/index.php?") ));
}
you are making it harder than it is. when you see what has to be done you'll kick yourself... =)
i cleaned up some of the tags in your main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/xlapps">
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/xlfx"
android:id="@+id/XLFx"/>
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/xlenlightenment"
android:id="@+id/XLEnlightenment"/>
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/xlfit"
android:id="@+id/XLFit"/>
<ImageButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/stylelife"
android:id="@+id/XLife"/>
</LinearLayout>
and your main activity called XLNetwork.java
Code:
public class XLNetwork extends Activity {
//Define some String Constants that will point to the website of your choice
public static final String XLF_X = "http://xlfx.30.forumer.com/index.php?";
public static final String XL_ENLIGHTENMENT = "http://www.facebook.com/enlightenment2011?ref=ts";
public static final String XL_FIT = "http://xlfx.30.forumer.com/index.php?";
public static final String X_LIFE = "http://xlfx.30.forumer.com/index.php?";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageButton b1 = (ImageButton) findViewById(R.id.XLFx);
linkOnButtonPress(b1, XLF_X);
ImageButton b2 = (ImageButton) findViewById(R.id.XLEnlightenment);
linkOnButtonPress(b2, XL_ENLIGHTENMENT);
ImageButton b3 = (ImageButton) findViewById(R.id.XLFit);
linkOnButtonPress(b3, XL_FIT);
ImageButton b4 = (ImageButton) findViewById(R.id.XLife);
linkOnButtonPress(b4, X_LIFE);
}
/*
* linkOnButtonPress()
*
* i made this so i wouldnt have to type the same process over and over.
* what gets passed is the reference to the button you want, and the web address you
* want the button to link to.
*
*/
private void linkOnButtonPress(ImageButton button, final String webSite) {
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent( Intent.ACTION_VIEW , Uri.parse(webSite) ));
}
});
}
}
i cant thank you enough, you were a lifesaver!!
I am a newbie in android dev.
I want to develop a very small and simple discount rate calculator.
in which there will be drop down menu with options like:
calculate 10%
calculate 20%
calculate 30%
Based on the selection of option from the drop down menu the discount rate should change.
After selection, there will be a textbox which should ask user to enter price.
and on the click even of "Calculate" button, the resultant amount (discounted rate) should be displayed.
I guess it is very simple for you guys. If anyone can help me with the code, i will deeply appreciate.
thank you
ok this is what I have done till now:
I created an Android Project names as :MyDC
MyDC.java
Code:
package com.super.mydc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class MyDC extends Activity {
private EditText amount1;
private double x=0;
private double y=2.0;
private double z=0;
private TextView tt;
private Button calculate;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// We want to view some very simple text, so we need a TextView
TextView tv = new TextView(this);
// Put some text to the newly created TextVIew
tv.setText("Test");
// Tell our Application to display the textView
this.setContentView(tv);
super.onCreate(icicle);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
amount1=(EditText)findViewById(R.id.amount1);
tt=(TextView)findViewById(R.id.tt);
calculate=(Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) { calculate();}});
}
private void calculate()
{
x=Double.parseDouble(amount1.getText().toString());
z=x-(x*y/100);
tt.setText(Double.toString(z));
}
}
This is main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spinner1"></Spinner>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter the price"
/>
<EditText android:layout_height="wrap_content" android:id="@+id/amount1" android:text="" android:layout_width="match_parent"></EditText>
<Button android:text="Calculate Result" android:id="@+id/calculate" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<EditText android:layout_height="wrap_content" android:id="@+id/tt" android:text="" android:layout_width="match_parent"></EditText>
</LinearLayout>
This is string.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hi, MyDC!</string>
<string name="app_name">My, DC</string>
<string name="spinner1">Choose discount type</string>
</resources>
This is what I am able to get:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
I am able to calculate discount on the button click, BUT i have hardcoded the discount rate.
I want to select discount rate based on the dropdown menu (I don't know how to set dropdown values with different discount rate in this problem)
In the dropdown menu I would like to have values like this:
Type 1 discount
Type 2 discount
Type 3 discount
Here is the respective discount rate for the above drop-down values:
Type 1 discount - 10%
Type 2 discount - 15%
Type 3 discount - 18%
PLZ HELP ME
Ok somehow I was able to add spinner tool on my application.
Now the question is how to select discount rate based on selected value from spinner.
PLZ HELP ME WITH THE CODE
Here is my current code:
MyDC.java
Code:
package com.super.mydc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class MyDC extends Activity {
private EditText amount1;
private double x=0;
private double y=2.0;
private double z=0;
private TextView tt;
private Button calculate;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// We want to view some very simple text, so we need a TextView
TextView tv = new TextView(this);
// Put some text to the newly created TextVIew
tv.setText("Test");
// Tell our Application to display the textView
this.setContentView(tv);
super.onCreate(icicle);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
initControls();
}
private void initControls()
{
amount1=(EditText)findViewById(R.id.amount1);
tt=(TextView)findViewById(R.id.tt);
calculate=(Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) { calculate();}});
}
private void calculate()
{
x=Double.parseDouble(amount1.getText().toString());
z=x-(x*y/100);
tt.setText(Double.toString(z));
}
}
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spinner1"></Spinner>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="@string/planet_prompt"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/planet_prompt"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter the price"
/>
<EditText android:layout_height="wrap_content" android:id="@+id/amount1" android:text="" android:layout_width="match_parent"></EditText>
<Button android:text="Calculate Result" android:id="@+id/calculate" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<EditText android:layout_height="wrap_content" android:id="@+id/tt" android:text="" android:layout_width="match_parent"></EditText>
</LinearLayout>
strings.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hi, MyDC!</string>
<string name="app_name">My, DC</string>
<string name="spinner1">Choose a planet</string>
<string name="planet_prompt">Choose a planet</string>
<string-array name="planets_array">
<item>10% discount A</item>
<item>15% discount B</item>
<item>18% discount C</item>
</string-array>
</resources>
Anyone ? Please Help ?
Im sorry to not be of very much help I studied java as a highschool unfortunately it was senior year and I am good at slacking. I would like to add suggestions though. first off i would try to find someway of implementing a way to get closer increments such as 5 or 1 %. such as a text box. let me sift through your code and see what i can see. are you having specific errors or what. we need some info.
Ok i looked at your code and im having a hard time reading it just because it isnt the norm that I look at. first off ya need to name your variables more recognizable things then x and y. that will make coding immensely more easy. also I am not seeing where you gathered the information from the drop down or spinner. at some point in the code you have to collect the information from the drop down or spinner and use it for the percent. also i didn't see any point where you gave the drop down any values. if you have any questions or anything feel free to pm I have xda app on my phone so even if not im not online ill get a notification on my phone.
{SBR}_L3GION said:
Ok i looked at your code and im having a hard time reading it just because it isnt the norm that I look at. first off ya need to name your variables more recognizable things then x and y. that will make coding immensely more easy. also I am not seeing where you gathered the information from the drop down or spinner. at some point in the code you have to collect the information from the drop down or spinner and use it for the percent. also i didn't see any point where you gave the drop down any values. if you have any questions or anything feel free to pm I have xda app on my phone so even if not im not online ill get a notification on my phone.
Click to expand...
Click to collapse
Hi,
Yes, I know I haven't defined values to drop down because that is the thing I need help with.
I also posted above this:
"Now the question is how to select discount rate based on selected value from spinner.
PLZ HELP ME WITH THE CODE"
I need help - How to define discount rate based on selection of drop down values.
Please help me with the code....
I also tried doing this quite awhile with an app I was writing and then discovered I had not enough experience to with the android system to write the program I should look it up and fix both of our programs but I've had a migraine for days and I'm just getting close to sleeping but when I get a chance I will look up giving values to the drop down and collecting them unless you want to google it first.
Sent from my Synergized xda Premium Evo
I have tried to find the solution on google but didn't get anything but somehow from google I was able to do (whatever I did above)
thanks, I think that would be great, if you can test my program on your side by that we both will be on the same page.
That's fine, you can test it whenever you get some time.
I appreciate your help!
I would setup radio buttons for the discount percentages
0 10% 0 20% etc.
Name each radio button and use a case statement to set a float to it's value:
switch(radioGroupName) {
case 10Percent:
int discountValue = .10
break;
...
Then do something like:
int discountedAmount = usersAmount - (usersAmount * discountValue);
Try this code.
myDC.java
Code:
package com.mydc;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;
public class myDC extends Activity {
double initial_price;
double discount;
double final_price;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.discount, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos==0){
discount=10;
}
else if (pos==1){
discount=15;
}
else if (pos==2){
discount=18;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Button calculate = (Button) findViewById(R.id.calculate);
calculate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
EditText amount1 = (EditText) findViewById(R.id.amount1);
if (amount1.length()>0 ) {
initial_price=Double.parseDouble(amount1.getText().toString());
TextView final_price_text = (TextView) findViewById(R.id.final_price);
final_price=initial_price-(initial_price*discount/100);
final_price_text.setText("Final Price : "+final_price);
}
else {
Toast.makeText(getBaseContext(), "Please enter price", Toast.LENGTH_SHORT).show();
}
}
});
}
}
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner1"></Spinner>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter the price" />
<EditText
android:layout_height="wrap_content"
android:id="@+id/amount1"
android:text=""
android:layout_width="match_parent"
android:numeric="decimal"></EditText>
<Button
android:text="Calculate Result"
android:id="@+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<TextView
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent"
android:id="@+id/final_price"></TextView>
</LinearLayout>
strings.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, main!</string>
<string name="app_name">myDC</string>
<string-array name="discount">
<item>10% discount A</item>
<item>15% discount B</item>
<item>18% discount C</item>
</string-array>
</resources>
Re: Need Help
Hello nemoc 23 ,
Firstly thank you very much for replying back with a solution.
It did work and solved my problem upto some extend.
Now what I only want 2 things to be done:
1) Right now, if we enter price in decimal or anything, if the final result is in decimal, it is being displayed as EXACT something like 99.9999999
How to limit the RESULT upto 2 decimal points only ?
2) What I am trying to do is to have this calculator on 3 different pages (in each page I will just modify the discounted rate). So I want a homepage (which will work as MENU) with 3 or 4 buttons and each button should be connected with specific page that will have ITS OWN above discount calculator.
Could you please show me how to create a homepage screen (which will work as MENU) and 3 or 4 buttons on it which are linked with different pages (in each page you can copy the same above calculator and I will modify the rate by myself)
thank you
Why 3 pages? Just do this:
Enter discount amount: ___________
Enter discount rate:______
Discounted Amount: ___________
Easy peasy.
Rootstonian said:
Why 3 pages? Just do this:
Enter discount amount: ___________
Enter discount rate:______
Discounted Amount: ___________
Easy peasy.
Click to expand...
Click to collapse
I know it is easy but it is not what I am looking for. My requirement is what I posted above. Thanks
Help
Hello nemoc 23 ,
Just giving you an update. I did try the tutorial you asked me to try. I am having some problem in it which you can see here: http://forum.xda-developers.com/showthread.php?p=15612542
Coming back my question (this calculator topic) - I created a screen layout to give you an idea what I want to do and need your help with.
This is what I want to do:
In this each button click will open separate page (or I guess it is called activity). I have mentioned on button what each button will open.
Please help me. thanks
Intent i = new Intent(this, calculator1.class);
startActivity(i);
You are still better off creating just ONE new Activity and passing to it which calculator you want to run. It is poor programming to code 3 activities when one will suffice. You'll need "extras" to do this.
Need Help
Ok somehow I was able to code for this problem but I am not getting desired output.
I have 3 buttons on my welcome screen "calculator", "calculator2", "exit" - My buttons are not working, I don't know why.
**Below is my complete code / programs:**
**welcome.java**
Code:
package com.testcalculator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class welcome extends Activity implements OnClickListener
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome1);
//////// MENU //////////
Button playBtn = (Button) findViewById(R.id.playBtn);
playBtn.setOnClickListener(this);
Button playBtn2 = (Button) findViewById(R.id.playBtn);
playBtn2.setOnClickListener(this);
Button exitBtn = (Button) findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(this);
}
/**
* Listener for game menu
*/
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.playBtn :
i = new Intent(this, testcalculator.class);
startActivity(i);
break;
case R.id.playBtn2 :
i = new Intent(this, testcalculator2.class);
startActivity(i);
break;
case R.id.exitBtn :
finish();
break;
}
}
}
**welcome1.xml**
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id ="@+id/playBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculator"
/>
<Button
android:id ="@+id/playBtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculator2"
/>
<Button
android:id ="@+id/exitBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit"
/>
</LinearLayout>
**testcalculator.java**
Code:
package com.testcalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;
public class testcalculator extends Activity {
double initial_price;
double discount;
double final_price;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.discount, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos==0){
discount=10;
}
else if (pos==1){
discount=15;
}
else if (pos==2){
discount=18;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Button calculate = (Button) findViewById(R.id.calculate);
calculate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
EditText amount1 = (EditText) findViewById(R.id.amount1);
if (amount1.length()>0 ) {
initial_price=Double.parseDouble(amount1.getText().toString());
TextView final_price_text = (TextView) findViewById(R.id.final_price);
final_price=initial_price-(initial_price*discount/100);
final_price_text.setText("Final Price : "+final_price);
}
else {
Toast.makeText(getBaseContext(), "Please enter price", Toast.LENGTH_SHORT).show();
}
}
});
}
}
**testcalculator.xml**
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner1"></Spinner>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter the price" />
<EditText
android:layout_height="wrap_content"
android:id="@+id/amount1"
android:text=""
android:layout_width="match_parent"
android:numeric="decimal"></EditText>
<Button
android:text="Calculate Result"
android:id="@+id/calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<TextView
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent"
android:id="@+id/final_price"></TextView>
</LinearLayout>
**testcalculator2.java**
Code:
package com.testcalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import android.widget.Toast;
public class testcalculator2 extends Activity {
double initial_price;
double discount2;
double final_price2;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.discount2, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (pos==0){
discount2=20;
}
else if (pos==1){
discount2=25;
}
else if (pos==2){
discount2=28;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Button calculate2 = (Button) findViewById(R.id.calculate2);
calculate2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
EditText amount2 = (EditText) findViewById(R.id.amount2);
if (amount2.length()>0 ) {
initial_price=Double.parseDouble(amount2.getText().toString());
TextView final_price_text = (TextView) findViewById(R.id.final_price2);
final_price2=initial_price-(initial_price*discount2/100);
final_price_text.setText("Final Price : "+final_price2);
}
else {
Toast.makeText(getBaseContext(), "Please enter price", Toast.LENGTH_SHORT).show();
}
}
});
}
}
**testcalculator2.xml**
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner2"></Spinner>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter the price" />
<EditText
android:layout_height="wrap_content"
android:id="@+id/amount2"
android:text=""
android:layout_width="match_parent"
android:numeric="decimal"></EditText>
<Button
android:text="Calculate Result"
android:id="@+id/calculate2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<TextView
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent"
android:id="@+id/final_price2"></TextView>
</LinearLayout>
**AndroidManifest.xml**
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.testcalculator"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".welcome"
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=".testcalculator" />
<activity android:name=".testcalculator2" />
</application>
</manifest>
**strings.xml**
Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, testcalculator!</string>
<string name="app_name">testcalculator</string>
<string-array name="discount">
<item>10% discount A</item>
<item>15% discount B</item>
<item>18% discount C</item>
</string-array>
<string-array name="discount2">
<item>20% discount A</item>
<item>25% discount B</item>
<item>28% discount C</item>
</string-array>
</resources>
**main.xml**
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
When I click Button1 "Calculator" - I get error saying ""The application testcalculator (process com.testcalculator) has stopped unexpectedly. Please try again.""
Button2 "Calculator2" doesn't do anything and same with 3rd button "exit:
**Please help me!!!**
You got a couple options. First instead of the startActivity() throw in a Toast so you can see if your onClick() is ok. You can also throw some inline clicklisteners (anonymous inner class) inside the setOnClickListener() instead of using 'this'. I find that way is a bit easier to organize.
Annd might I suggest you follow the Java guidelines for capitalisation of class names. Its confusing when reading your code and seeing testcalculator.class when usually instances of objects are lower case while the class name is capitalized. Like TestCalculator.class
From something awesome
Hello,
is there a possibility to show the tabs from a TabHost next to each other, when the phone is in landscape-orientation?
Auroratic said:
Hello,
is there a possibility to show the tabs from a TabHost next to each other, when the phone is in landscape-orientation?
Click to expand...
Click to collapse
I don't think there is. I haven't seen anyone do this yet, and it would only be confusing... Three tabs, two displayed at the same time is weird and takes away half the displayed content of one tab.
Anyhow, why use a TabHost? That's been deprecated for a long while, with the introduction of the ActionBar.
bassie1995 said:
I don't think there is. I haven't seen anyone do this yet, and it would only be confusing... Three tabs, two displayed at the same time is weird and takes away half the displayed content of one tab.
Click to expand...
Click to collapse
see the image I attached, i hope you understand what I'm trying to do
bassie1995 said:
Anyhow, why use a TabHost? That's been deprecated for a long while, with the introduction of the ActionBar.
Click to expand...
Click to collapse
oh I don't know that..
Auroratic said:
see the image I attached, i hope you understand what I'm trying to do
oh I don't know that..
Click to expand...
Click to collapse
You can do that.
Have a look at Fragments. They are exactly what you want.
Just use a different layout for landscape.
pfuuu...that's too hard for me.
can you create a sample application which uses ActionBar-tabs in portrait and shows the content of the tabs in landscape-mode?
Auroratic said:
pfuuu...that's too hard for me.
can you create a sample application which uses ActionBar-tabs in portrait and shows the content of the tabs in landscape-mode?
Click to expand...
Click to collapse
AB tabs can't show the content of multiple tabs at once, I think... Unless you do some intricate custom layout work, as nikwen said.
Auroratic said:
pfuuu...that's too hard for me.
can you create a sample application which uses ActionBar-tabs in portrait and shows the content of the tabs in landscape-mode?
Click to expand...
Click to collapse
to expand on nikwen's answer what you need to do is have a layout file for listview and a layout file for portrait and landscape. To do the portrait and landscape you put the portrait file in the layout folder and create a layout-land folder. In the portrait file you would put one fragment and in the landscape file you would 5 (according to your image) fragments and you could put a textview above each if you are going to remove the tabs.
Action bar tabs are programmatically inserted so you would have to listen for orientation change and remove them when in landscape.
here are some resources that will help you:
Fragments:
Android guide to fragments
Android references for fragments
Vogella fragments tutorial
Action Bar Tabs:
Android Action Bar Guide
Android references for AB Tabs
Vogella Action Bar tutorial
and here are some resources for finding out orientation:
Android Configuration references
Android guide to handling configuration change
I have no rewritten my app and now its using action bar tabs and its creating a fragment 5 times with different data. How should i make the layout for landscape and how should i insert the fragments into the layout?
Thank you.
make a layout-land folder and create a custom layout for landscape
a horizontal linear layout with all the fragments would do
warlock9_0 said:
a horizontal linear layout with all the fragments would do
Click to expand...
Click to collapse
What should be in this file? In portrait I'm using a viewpager, which contains the fragments.
PORTRAIT FILES
act_viewpager.xml:
Code:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".KlassenAnzeige" />
site_fragment.xml:
Code:
<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"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="8dp"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_marginTop="8dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:listSelector="@android:color/transparent" />
</RelativeLayout>
the site_fragment is used for all fragment in the viewpager
MainActivity
Code:
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
@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;
}
@Override
protected void onResume() {
super.onResume();
if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.odd, new OddNumbers()).commit();
manager.beginTransaction().replace(R.id.even, new EvenNumbers()).commit();
manager.beginTransaction().replace(R.id.alpha, new Alpha()).commit();
}
}
}
layout-land/activity_main.xml
Code:
<LinearLayout xmlns:android="...."
xmlns:tools="...."
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:baselineAligned="false"
android:orientation="horizontal" >
<FrameLayout android:id="@+id/odd"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<FrameLayout android:id="@+id/even"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<FrameLayout android:id="@+id/alpha"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
</LinearLayout>
one of the fragments
Code:
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class EvenNumbers extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
String[] values = new String[] { "2", "4", "6","8","10","12","14","16","18","20","22" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,values);
/** Setting the list adapter for the ListFragment */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Hello,
I create that thread to present you a tutorial learning you how to Auto Restart an Android App after a Crash or a Force Close Error. You can also discover this tutorial and the demo video associated directly on Youtube :
How to auto restart an Android Application after a Crash or a Force Close Error ?
The biggest nightmare of Android developers is the Crash or Force Close Error that can occur when a user uses one of their applications. Indeed, it’s always a bad message sent to the user and the major risk is that the user uninstalls the application. Unfortunately, you can’t always catch properly all errors and sometimes you can’t avoid a Crash or a Force Close Error. In these specific cases, a good approach is to configure auto restart for your Android Application. With this approach, you have better chances to keep users on your application.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
To start, you need to create a custom Application class implementation to get an instance of your context continuously :
Code:
package com.ssaurel.appcrash;
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
public static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
@Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
public static MyApplication getInstance() {
return instance;
}
}
Don’t forget to add this Application implementation on your Android Manifest :
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ssaurel.appcrash">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name=".MyApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
To try the auto restart feature, we need to define a button in the layout of the Main Activity. When we will click on the button, we’re going to crash the application. The layout will have the following form :
Code:
<?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:id="@+id/activity_main"
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.ssaurel.appcrash.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Crash Me !"
android:onClick="crashMe"/>
</RelativeLayout>
Now, we enter in the core of our auto restart feature. You need to create a custom implementation of the UncaughtExceptionHandler interface. What is the purpose of this interface ? It’s an interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
Our custom implementation will have the following form :
Code:
package com.ssaurel.appcrash;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
private Activity activity;
public MyExceptionHandler(Activity a) {
activity = a;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Intent intent = new Intent(activity, MainActivity.class);
intent.putExtra("crash", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(MyApplication.getInstance().getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr = (AlarmManager) MyApplication.getInstance().getBaseContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
activity.finish();
System.exit(2);
}
}
When an uncaught exception occurs, the uncaughtException method will be called. We’re going to create an Intent to restart our application at the defined moment via an Alarm. Then, we finish the current activity and we exit the application. Note that we put a boolean parameter to indicate that the application is restarted.
Last step is to install the UncaughtExceptionHandler during the start of the application by calling the static setDefaultUncaughtExceptionHandler method of the Thread class :
Code:
package com.ssaurel.appcrash;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
if (getIntent().getBooleanExtra("crash", false)) {
Toast.makeText(this, "App restarted after crash", Toast.LENGTH_SHORT).show();
}
}
public void crashMe(View v) {
throw new NullPointerException();
}
}
Note that we launch a NullPointerException in the crashMe method to force the crash of the application and test the auto restart feature. Other thing to note is the crash boolean parameter test when the activity is launched. Like said previously, it lets us to know when the application is restarted after a crash or when the application is launched for the first time.
Now, you can launch the application and you should see the following screen after a click on the crashMe button :
Don't hesitate to give it a try and give me your feedbacks if you have some ideas for new tutorials.
Thanks.
Sylvain
Really good guide, it resembles an implementation I had of a simple "restart" feature in my app. Only thing I'm wondering is why does System.exit if given enough time before the activity is restarted (in my case roughly AlarmManager.RTC, System.currentTimeMillis() + ~ 1.5 seconds) will display the annoying "Unfortunately XYZ has stopped" and prevent the application from fully starting until OK is clicked? Is there any potential risk or downside to setting the alarm manager delay to only +100? I'm thinking something along the lines of not enough time to flush resources?
Hello,
In that tutorial, you are going to learn how to create an Anagram game for Android by using Android Studio.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
But what is an Anagram ?
An anagram is direct word switch or word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example, the word anagram can be rearranged into “nag a ram”.
Note that you can discover this tutorial in video on YouTube :
Create the User Interface
To start, we are going to create the User Interface of our Anagram game. In our User Interface, we will have a TextView to display the anagram. Then, an EditText to let the users to enter the word they found. And finally both buttons : one to validate the word entered and another to start a new game.
We make some customizations on these views. For example, we center them horizontally and this gives us the following code :
Code:
<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"
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=".MainActivity" >
<TextView
android:id="@+id/wordTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Word To Find"
android:textSize="22sp"
android:textStyle="bold" />
<EditText
android:id="@+id/wordEnteredEt"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/wordTv"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:inputType="textCapCharacters" />
<Button
android:id="@+id/validate"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/wordEnteredTv"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="Validate" />
<Button
android:id="@+id/newGame"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/validate"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="New Game" />
</RelativeLayout>
Core of the Anagram Game
Now, we can create the core of our game : the Anagram class. We will use this class to generate new words to find and to shuffle the word to find. Note that the list of words used for the game will be defined in this class :
Code:
package com.ssaurel.anagram;
import java.util.Random;
/**
* Created by ssaurel on 05/09/2017.
*/
public class Anagram {
public static final Random RANDOM = new Random();
public static final String[] WORDS = {"ACCOUNT", "ADDITION",
"AGREEMENT", "ANGRY", "ANIMAL", "BEHAVIOUR", "BETWEEN", "BLACK", "CHEMICAL", "FOOLISH",
"FREQUENT", "GOVERNMENT", "GRAIN", "GRASS", "HOSPITAL", "PAYMENT", "POLITICAL",
"PROCESS", "SHAME", "SMASH", "SMOOTH", "STATEMENT", "SUBSTANCE", "TEACHING", "TENDENCY",
"TOMORROW", "TOUCH", "UMBRELLA", "WEATHER", "YESTERDAY"};
public static String randomWord() {
return WORDS[RANDOM.nextInt(WORDS.length)];
}
public static String shuffleWord(String word) {
if (word != null && !"".equals(word)) {
char a[] = word.toCharArray();
for (int i = 0; i < a.length; i++) {
int j = RANDOM.nextInt(a.length);
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return new String(a);
}
return word;
}
}
Code of the Main Activity
Now, we can write the Java code of the main activity. The code is pretty simple. We get references of the views in the onCreate method. Then we install OnClickListener for both buttons.
In the validate method, we are going to check if the word entered by the user if equal to the word to find. If yes, we display a message of congratulations to the user and we start a new game by calling the newGame method.
The newGame method is used to start a new Anagram game. We generate a random word to find by calling the randomWord method of the Anagram class. Then, we shuffle this word via the shuffleWord method of the Anagram class. Finally, we display the word shuffled on the screen. The game starts and the user must find the word.
This gives us the following code :
Code:
package com.ssaurel.anagram;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView wordTv;
private EditText wordEnteredTv;
private Button validate, newGame;
private String wordToFind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wordTv = (TextView) findViewById(R.id.wordTv);
wordEnteredTv = (EditText) findViewById(R.id.wordEnteredEt);
validate = (Button) findViewById(R.id.validate);
validate.setOnClickListener(this);
newGame = (Button) findViewById(R.id.newGame);
newGame.setOnClickListener(this);
newGame();
}
@Override
public void onClick(View view) {
if (view == validate) {
validate();
} else if (view == newGame) {
newGame();
}
}
private void validate() {
String w = wordEnteredTv.getText().toString();
if (wordToFind.equals(w)) {
Toast.makeText(this, "Congratulations ! You found the word " + wordToFind, Toast.LENGTH_SHORT).show();
newGame();
} else {
Toast.makeText(this, "Retry !", Toast.LENGTH_SHORT).show();
}
}
private void newGame() {
wordToFind = Anagram.randomWord();
String wordShuffled = Anagram.shuffleWord(wordToFind);
wordTv.setText(wordShuffled);
wordEnteredTv.setText("");
}
}
Play to our Anagram Game
Now, it’s time to play to our Anagram Game. We launch the Anagram Game on an Android device and we see the following screen :
We have to enter the word to find in the EditText and then clicking to the validate button to win the game.
That’s all for that tutorial. To discover more tutorials on Android Development, don’t hesitate to subscribe to the SSaurel’s Channel on YouTube : https://www.youtube.com/channel/UCXoh49OXVg1UGjgWX1JRvlw
You can also discover this tutorial directly on the SSaurel's Blog : https://www.ssaurel.com/blog/learn-to-create-an-anagram-game-for-android/
Don't hesitate to give it a try and give me your feedback.
Thanks.
Sylvain