[Tutorial] Learn how to create a Blink Effect on Android - Android Software Development

Hello,
I create that thread to offer you a tutorial aiming to learn you how to create a Blink Effect on Android. Like usual, you can also enjoy this tutorial in video on Youtube :
Create a Blink Effect on Android
Like you must know, users always enjoy cool effects on interfaces. Adding some effects on your Android application can be a good way to make your application different from others. Previously, we have seen how to create a type writer effect and a blur effect. In this tutorial, you are going to learn how to create a blink effect on Android. It will be also a good way to discover how to use Animations.
First, we create a layout with a TextView that will receive the blink effect and a Button to start the blink effect :
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ssaurel.blinkeffect.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Blink Effect with SSaurel "
android:textSize="22sp"
android:layout_centerInParent="true"
android:id="@+id/txt"
/>
<Button
android:text="Blink Effect !"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:layout_below="@id/txt"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Now, it's time to write the code for the blink effect in an Activity. To make a blink effect, we can use the ObjectAnimator object of Android SDK that lets us to animate a specific property of a View. Here, we need to animate the backgroundColor property of the TextView. In the ObjectAnimator, we can also define colors we want to apply to the background, duration of the animation, evaluator, repeat mode and repeat count. Here, we create an infinite animation. The code of the blink effect animation should be like that :
Code:
ObjectAnimator anim = ObjectAnimator.ofInt(txt, "backgroundColor", Color.WHITE, Color.RED,
Color.WHITE);
anim.setDuration(1500);
anim.setEvaluator(new ArgbEvaluator());
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
anim.start();
The complete code for the Activity is the following :
Code:
package com.ssaurel.blinkeffect;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView txt;
private Button blinkBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.txt);
blinkBtn = (Button) findViewById(R.id.btn);
blinkBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
manageBlinkEffect();
}
});
}
private void manageBlinkEffect() {
ObjectAnimator anim = ObjectAnimator.ofInt(txt, "backgroundColor", Color.WHITE, Color.RED,
Color.WHITE);
anim.setDuration(1500);
anim.setEvaluator(new ArgbEvaluator());
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
anim.start();
}
}
Finally, you can launch the application and enjoy your cool blink effect .
Don't hesitate to give it a try and give me your feedbacks.
Thanks.
Sylvain

Some feedbacks ?

Related

[Question] Having trouble setting up wallpaper chooser/picker in eclipse

Doing a theme for ADW and want to include a wallpaper chooser so the user can browse through my wallpaper set...
I am working in eclipse.
I have successfully got setup in wallpaper menu (when you press and hold homescreen, select wallpaper, Then you see the option for wallpaper i have setup)
BUT when click i get a force close...
I have 10 wallpapers in my drawable-hdpi folder. they are named
wallpaper1
wallapper2
etc...
I also have my wallpaper1_small, etc... set up too..
This is contents of my wallpaper_chooser.xml in layout
Code:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:id="@id/wallpaper" android:layout_width="fill_parent" android:layout_height="0.0dip" android:scaleType="fitCenter" android:layout_weight="1.0" />
<Gallery android:id="@id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" />
<Button android:layout_gravity="center_horizontal" android:id="@id/set" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Set wallpaper" />
</LinearLayout>
This is my wallpaper_item.xml in layout
Code:
<?xml version="1.0" encoding="UTF-8"?>
<ImageView android:background="?android:galleryItemBackground" android:focusable="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:scaleType="fitXY"
xmlns:android="http://schemas.android.com/apk/res/android" />
this is my arrays.xml in values-hdpi folder
Code:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<string-array name="wallpapers">
<item>wallpaper1</item>
<item>wallpaper2</item>
<item>wallpaper3</item>
<item>wallpaper4</item>
<item>wallpaper5</item>
<item>wallpaper6</item>
<item>wallpaper7</item>
<item>wallpaper8</item>
<item>wallpaper9</item>
<item>theme_wallpaper</item>
</string-array>
</resources>
Any Idea's??
okay, figured out i needed a wallpaper.java reference...
Added the following
Code:
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package bigdx.adw.crystalx;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Gallery.LayoutParams;
import java.io.IOException;
import java.io.InputStream;
/**
* Wallpaper picker for the Home application. User can choose from
* a gallery of stock photos.
*/
public class wallpaper extends Activity implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String LOG_TAG = "Home";
private static final Integer[] THUMB_IDS = {
R.drawable.wallpaper1_small,
R.drawable.wallpaper2_small,
R.drawable.wallpaper3_small,
};
private static final Integer[] IMAGE_IDS = {
R.drawable.wallpaper1,
R.drawable.wallpaper2,
R.drawable.wallpaper3,
};
private Gallery mGallery;
private boolean mIsWallpaperSet;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setOnItemClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
getWindow().setBackgroundDrawableResource(IMAGE_IDS[position]);
}
public void onItemClick(AdapterView parent, View v, int position, long id) {
selectWallpaper(position);
}
/*
* When using touch if you tap an image it triggers both the onItemClick and
* the onTouchEvent causing the wallpaper to be set twice. Synchronize this
* method and ensure we only set the wallpaper once.
*/
private synchronized void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(IMAGE_IDS[position]);
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to set wallpaper " + e);
}
}
public void onNothingSelected(AdapterView parent) {
}
@Override
public boolean onTouchEvent(MotionEvent event) {
selectWallpaper(mGallery.getSelectedItemPosition());
return true;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return THUMB_IDS.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(THUMB_IDS[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(android.R.drawable.picture_frame);
return i;
}
}
}
It goes into the wallpaper picker without getting FC but after sliding the wallpapers on bottom it goes away all of a sudden...
One note is that the following code was originally R.layout.wallpaper, BUT get error...
changed to (setContentView(R.layout.wallpaper_chooser)
Is this that difficult?
or just not that common?
or maybe i should be more familiar with how apk's work?
Any help is appreciated...
bignadad said:
..One note is that the following code was originally R.layout.wallpaper, BUT get error...
changed to (setContentView(R.layout.wallpaper_chooser)
Click to expand...
Click to collapse
what error?
rori~ said:
what error?
Click to expand...
Click to collapse
wallpaper cannot be resolved or is not a field...
thanks for the reply..

[Q] Need help with discount calculator

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

[Q] Choose a string in spinner

Hey guys!
I am working on my first app, cut me some slack for asking please .
So I'm stuck on a little problem:
I have a reader activity and I put a spinner on top of the screen to choose the string where the text comes from:
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:id="@+id/kapitelspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/kapitel_prompt" />
<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/kapitel1"
/>
</ScrollView>
</LinearLayout>
The TextView in the ScrollView is supposed to be the selected text from the spinner.
Code:
package com.asm.reader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class BookActivity extends Activity {
static final private int CHOOSE_KAPITEL = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_activity);
Spinner spinner = (Spinner) findViewById(R.id.kapitelspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.kapitel_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
}
Code:
package com.asm.reader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext(),
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
I'm trying to make the spinner choose the string of the textview but i have no idea how to do it. (Already did the toast part)
If anyone could help me it would be greatly appreciated!
Thanks !
bump. the last problem im stuck on
The way I understand what you're trying to do is select an item from the spinner, and set the TextView according to the selected spinner item.
If that is the case you will, for starters, need to set an id attribute for the TextView in the layout xml file.
Then within your onItemSelected() method you need to create a reference to the TextView the same way you did it with the spinner; using the findViewById() method.
Then using that reference you can set the text of the TextView using the same string you got when you created the Toast notification.
Hope that helps!

[GUIDE] Clearable EditTexts

Hello everyone,
As most of you probably have, I have been working on an app that lets users input text in an EditText. However, this app possibly gets a lot of input from the user, which can lead to multiple lines of text in either of two EditTexts!
Naturally, this can result in some real headaches: when you want to clear the EditText, you'll have to delete character after character from it.
So, I decided to go on a quest. Hunt down a solution that's fat, easy to implement and works nicely from the user's prespective. Of course, it'd be nice if it looks cool, too.
This is where I came across a blog post, after some browsing of StackOverflow, that detailed a nice and quick fix.
Today, I will be explaining to all of you how to implement this, and even add a couple of little extras.
Step 1: Creating the custom View's XML layout
The first thing you have to do, since this is a custom View, is create its XML layout. Luckily, this isn't too hard:
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/clearable_edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="35dip" />
<Button
android:id="@+id/clearable_button_clear"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dip"
android:background="@drawable/ic_clear" />
</RelativeLayout>
Some explanation: This is just a layout declaration. Later on, when making the ClearableEditText constructor, you'll have to call upon the elements in this layout.
Step 2: Making the class
To create an own new View, you have to extend from one of the standard View classes. Since you are including a Button and EditText in the one (creating a compound View), RelativeLayout is a good choice.
In the constructors of the class - which overrides the stock EditText constructors - is where you inflate the layout, which has been done by adding a method initViews().
The method to pay attention to here is showHideClearButton. An addTextChangedListener call is made, which conveniently takes a TextWatcher as its parameter. That means we can easily see when something about the input changes, and act upon it.
Some methods have to be implemented, but onTextChanged is the only one we'll really need. Here, we can check the length of the String that's been entered, and see whether to hide or show to cross Button for clearing the EditText.
The code speaks for itself from here on out:
Code:
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class ClearableEditText extends RelativeLayout {
LayoutInflater inflater = null;
EditText edit_text;
Button btn_clear;
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initViews();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initViews();
}
public ClearableEditText(Context context) {
super(context);
initViews();
}
void initViews() {
inflater = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.clearable_edit_text, this, true);
edit_text = (EditText) findViewById(R.id.clearable_edit);
btn_clear = (Button) findViewById(R.id.clearable_button_clear);
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
clearText();
showHideClearButton();
}
void clearText() {
btn_clear.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
edit_text.setText("");
}
});
}
void showHideClearButton() {
edit_text.addTextChangedListener(new TextWatcher() {
[user=439709]@override[/user]
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() > 0)
btn_clear.setVisibility(RelativeLayout.VISIBLE);
else
btn_clear.setVisibility(RelativeLayout.INVISIBLE);
}
[user=439709]@override[/user]
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
[user=439709]@override[/user]
public void afterTextChanged(Editable s) {
}
});
}
public Editable getText() {
Editable text = edit_text.getText();
return text;
}
}
Step 3: Using the ClearableEditText
So now, we have a (hopefully) fully functional implementation. We are still missing something, though! Of course, we haven't implemented our own solution into the code yet.
Luckily, this is very easy and takes mere seconds.
To use your ClearableEditText in a layout, simply add its full path to one of the elements, like so:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<[packagename].ClearableEditText
android:id=”@+id/edit_text_clearable”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
</LinearLayout>
See? Very easy. There is still one minor issue, though...
Step 4: Finishing touches - setting attributes
As you have probably eagerly tried, the above code should completely work and give you a working clearable EditText.
Of course, since there's no free lunch in computer science, there's a catch: no attributes can be set from your layout's XML file (the number of lines, text size, etc.).
So, I thought up a very simple way of doing this programatically, from your Java code. These supplements does take extra lines in your class' code, but will do exactly the same as their XML counterparts.
In your ClearableEditText class, to set the input type, hint and maximum number of lines, add:
Code:
public void setHint(int encode) {
edit_text.setHint(encode);
}
public void setMaxLines(int lines) {
edit_text.setMaxLines(lines);
}
public void setType(int type) {
edit_text.setInputType(type);
}
Then, in your main class, where you're calling those methods:
Code:
<editTextName>.setHint("Hello world!");
<editTextName>.setMaxLines(5);
<editTextName>.setType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
Keep in mind these are examples. The setType call will set the ClearableEditText to only receive numbers, which can be positive and negative (signed, after the sign bit in bit notation). I recommend you look up the API entry for it, or Google for it.
This can be done for - seemingly, mind - any type of attribute. I've used this for text size, number of lines, to get the text, and the above examples.
Should you have anymore questions or things to say about this, please do so!
Have fun,
bassie1995
P.S.: Big thanks to the creator of the original blog post. Thanks ab1209!

[Q] View tabs at landscape next to each other

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);
}
}

Categories

Resources