Java/Android - Hide a link as text - java

Hey guys I have been trying to figure this out and have looked over a number of questions here but can't seem to find the answer to my problem. I am making an app that displays dinners at random from an array. I would like these dinners to be clickable and take the user to a web page but I have no idea how to make that happen so at the moment I have just added the link below the dinner which looks pretty ugly.
Here is the class that contains the recipes:
package me.oak.dinnertime;
import java.util.Random;
public class CookBook {
public String[] mfood =
{
"Chicago Deep Dish Pizza \n \n http://www.taste.com.au/recipes/28896/chicago+deep+dish+pizza?ref=collections,pizza-recipes",
"Spaghetti Bolognese \n \n http://www.bbcgoodfood.com/recipes/1502640/the-best-spaghetti-bolognese",
"Bourbon Chicken \n \n http://www.food.com/recipe/bourbon-chicken-45809",
};
public String getFood() {
String food = "";
//Randomly select a dinner
Random randomGenerator = new Random(); //Construct a new Random number generator
int randomNumber = randomGenerator.nextInt(mfood.length);
//Convert random number to text
food = mfood[randomNumber];
return food;
}
}
And here is the main activity:
package me.oak.dinnertime;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DinnerTimeActivity extends Activity {
private CookBook mCookBook = new CookBook();
private ColourWheel mColourWheel = new ColourWheel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dinner_time);
final TextView dinnerLabel = (TextView) findViewById(R.id.DinnerTextView);
final Button showDinnerButton = (Button) findViewById(R.id.showDinnerButton);
final RelativeLayout relativelayout = (RelativeLayout) findViewById(R.id.relativeLayout);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String food = mCookBook.getFood();
//Update the label with the dinner
dinnerLabel.setText(food);
int colour = mColourWheel.getColour();
relativelayout.setBackgroundColor(colour);
showDinnerButton.setTextColor(colour);
}
};
showDinnerButton.setOnClickListener(listener);
}
}
And here is the XML file:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".DinnerTimeActivity"
android:background="#ff51b46d"
android:id="#+id/relativeLayout">
<TextView android:text="What&apos;s for dinner?" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#80ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/DinnerTextView"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="24sp"
android:textColor="#android:color/white"
android:text="Click the button to find out!"
android:autoLink="web" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dinner Time"
android:id="#+id/showDinnerButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#android:color/white"
android:textColor="#ff51b46d" />
</RelativeLayout>
Sorry to give you so much, I just hope someone can help me out.

To use the LinkMovementMethod, try following:
change your array list content from:
Chicago Deep Dish Pizza \n \n http://www.taste.com.au/recipes/28896/chicago+deep+dish+pizza?ref=collections,pizza-recipes
to:
Chicago Deep Dish Pizza
And when set this text to your TextView, do it as:
(Updated: remove the underline and change text color, source: Remove underline from links in TextView - Android)
Spannable s = (Spannable) Html.fromHtml(foodString);
for (URLSpan u: s.getSpans(0, s.length(), URLSpan.class)) {
s.setSpan(new UnderlineSpan() {
public void updateDrawState(TextPaint tp) {
//remove the underline
tp.setUnderlineText(false);
//set text color
tp.setColor(getResources().getColor(R.color.orange));
}
}, s.getSpanStart(u), s.getSpanEnd(u), 0);
}
dinnerLabel.setText(s);
dinnerLabel.setMovementMethod(LinkMovementMethod.getInstance());
Also remove the
android:autoLink="web"
in the xml.
As I have tested, "Chicago Deep Dish Pizza" will appear as a clickable link in the testview.

just use something like this in your string file and refrence it in the textview
<string name="links">Google shalom is a boyGoogle 2 </string>
you can also use this in an array in the strings file
to make it actually work do this
terms = findViewById(R.id.terms);
terms.setMovementMethod(LinkMovementMethod.getInstance());

I answered this on Hackforums for you.
Store the links in a separate array make sure the indexes of the links line up with the location in the other array. So:
public class CookBook {
public String[] mfood =
{
"Chicago Deep Dish Pizza",
"Spaghetti Bolognese",
"Bourbon Chicken",
};
public String[] mLinks =
{
"http://www.taste.com.au/recipes/28896/chicago+deep+dish+pizza?ref=collections,pizza-recipes",
"http://www.bbcgoodfood.com/recipes/1502640/the-best-spaghetti-bolognese",
"http://www.food.com/recipe/bourbon-chicken-45809",
};
public int getRandomFoodIndex() {
//Randomly select a dinner
Random randomGenerator = new Random(); //Construct a new Random number generator
int randomNumber = randomGenerator.nextInt(mfood.length);
//Convert random number to text
return randomNumber;
}
public String getFood(int index) {
return mfood[index];
}
public String getLink(int index) {
return mLinks[index];
}
}
and then
public class DinnerTimeActivity extends Activity {
private CookBook mCookBook = new CookBook();
private ColourWheel mColourWheel = new ColourWheel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dinner_time);
final TextView dinnerLabel = (TextView) findViewById(R.id.DinnerTextView);
final Button showDinnerButton = (Button) findViewById(R.id.showDinnerButton);
final RelativeLayout relativelayout = (RelativeLayout) findViewById(R.id.relativeLayout);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int index = mCookBook.getRandomFoodIndex();
String food = mCookBook.getFood(index);
String link = mCookBook.getLink(index);
//Update the label with the dinner
dinnerLabel.setText(food);
/** open link with the link variable */
int colour = mColourWheel.getColour();
relativelayout.setBackgroundColor(colour);
showDinnerButton.setTextColor(colour);
}
};
showDinnerButton.setOnClickListener(listener);
}
}

Related

flash cards showing blank card android

I am creating a flash card app in android.
For some reason when you hit the button for next card it will randomly show either the next card or a blank card. Sometimes it will be a whole heap of blank cards then one with information. Please find the code below. I am new to creating apps but have done java in the past, it works perfectly in netbeans but not when you run the app.
I want the cards to only appear once thats what the num arraylist is for, it holds the index numbers for the names arraylist. so it appears once but will show blank cards when it shouldnt be. eg: card with info, card without info, card with info. sometimes it will show multiple empty cards then one with info, that is my problem.
I know i havent commented the code,
The first activity:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Character.createArrays();
}
/**
* Called when the user taps the Start button
*/
public void sendMessage(View view) {
Character.getCharName();
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
}
}
The second activity where the cards are called:
public class DisplayMessageActivity extends AppCompatActivity {
public static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
;
}
public void refresh(View view) {
Character.getCharName();
overridePendingTransition(0, 0);
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
this.finish();
overridePendingTransition(0, 0);
}
The methods to get the cards, There are arraylists and the arrays are created correctly and the string arrays are inputted correctly. the CharacterNames array is just an array with names in them. the num array just has index numbers inputted and checked:
public void getCharName() {
RandomNumGen();
mMessage = "";
message = "";
while (num.contains(mRandom)) {
RandomNumGen();
}
for (int i = 0; i < CharacterNames.size(); i++) {
if (i == mRandom) {
mMessage = CharacterNames.get(i);
if (i == mRandom && CharacterNames.contains(mMessage)) {
num.add(mRandom);
card();
}
}
}
}
public void RandomNumGen() {
mRandom = (int) (Math.random() * CharacterNames.size());
}
public String card() {
String[] array;
for (int y = 0; y < names.size(); y++) {
if (Arrays.asList(names.get(y)).contains(mMessage)) {
array = (names.get(y));
for (String array1 : array) {
if (array1 != null && array1.length() > 0) {
message += "\n" + "\n" + (array1);
}
}
Arrays.fill(array, null);
}
}
return message;
}
I hope thats enough information to help.
Thank you so much for understanding an helping me
activity display message xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">
<TextView
android:id="#+id/textView"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="#string/textview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:onClick="refresh"
android:text="#string/next_char"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:text="Next character" />
</android.support.constraint.ConstraintLayout>
enter code here

Android TextView with limited amount of items and special functionality

I want to have a multiline text view and adding text to it,
After adding five lines to the TextView I want to start to add to the beginning of the text view.
For example: (numbers as text), 1,2,3,4,5 -> 6,2,3,4,5 -> 6,7,3,4,5 and so on.
I thought about using StringBuilder but I don't see an efficient way to implement this.
The delimiter of each row is "\n\n" maybe it will help to solve the problem.
Or maybe should I just do 5 textView's and have some switch case between them?
Button xml:
<TextView
android:id="#+id/searchesInputTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollHorizontally="false"
android:width="300dp"
android:height="200dp"
android:background="#drawable/border_style"
android:maxLines="5"
android:layout_marginTop="24dp"
/>
in MainActivity.java:
public class MainActivity extends AppCompatActivity {
private TextView searchesTextView;
private ImageButton refreshCurrentLocationButton;
private String myText = "";
refreshCurrentLocationButton = (ImageButton) findViewById(R.id.currentLocationRefreshImageButton);
searchesTextView = (TextView) findViewById(R.id.searchesInputTextView);
refreshCurrentLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Actual code
myText += location.ToString() + "\n\n";
searchesTextView.setText(myText);
});
}

How to change textView (digitalClock) color on touch(screen)

I'm making an app that just displays a clock, but I want is so that everytime a user touches the screen it changes the color of the text (from a list of preselected colors in a colors.xml file) but I haven't got a clue where to start. Can someone point me in the right direction?
Here's the main activity:
public class MainActivity extends Activity {
private static final Random RANDOM = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Handler handler = new RandomMoveHandler((TextView) findViewById(R.id.digitalClock1));
handler.sendEmptyMessage(0);
}
// Make the handler subclass static because of this: http://stackoverflow.com/a/11408340/111777
private static class RandomMoveHandler extends Handler {
private final WeakReference<TextView> textViewWeakReference;
private RandomMoveHandler(TextView textView) {
this.textViewWeakReference = new WeakReference<TextView>(textView);
}
#Override
public void handleMessage(Message msg) {
TextView textView = textViewWeakReference.get();
if (textView == null) {
Log.i(TAG, "WeakReference is gone so giving up.");
return;
}
int x = RANDOM.nextInt(350 - 100);
int y = RANDOM.nextInt(800 - 100);
Log.i(TAG, String.format("Moving text view to (%d, %d)", x, y));
textView.setX(x);
textView.setY(y);
//change the text position here
this.sendEmptyMessageDelayed(0, 30000);
}
}
private static final String TAG = MainActivity.class.getSimpleName();
}
and here's the layout xml:
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:background="#color/black" >
<DigitalClock
android:id="#+id/digitalClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DigitalClock"
android:textColor="#color/ics_blue"
android:textSize="28sp" />
I haven't making deal with DigitalClock but I think, at first, you should reference DigitalClock variable, not TextView. And second, to intercept touch event you need to override onTouckEvent method of your activity, it will callback everytime user touches the screen.
You should follow these steps
Use a TimerTask to.continusly show the time
Implement a touchlistener on that clock view
like this
view.setOnTouchListener
Make an array Colors like this
int[] colr={Color.BLACK,Color.BLUE};
and use random index in your touch event andset it as your color of the view

I need the same variable in multiple views, but it's not working

I'm trying to create an application that figures planetary weight. In the first view the user inputs their weight and it has an enter button, in the second view is a list of radio buttons and the select button. I want it to multiply their weight by the planet's force. To do this I needed the weight variable for both activity_main.xml and planets.xml. At first I had it in only planets, but now that it's in main as well, the if else statements are erroring.
activity_main.xml:
<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" >
<TextView
android:id="#+id/askwtTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="19dp"
android:text="#string/askwt" />
<EditText
android:id="#+id/inputwtEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/askwtTextView"
android:layout_below="#+id/askwtTextView"
android:layout_marginTop="26dp"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="#+id/enterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/inputwtEditText"
android:layout_below="#+id/inputwtEditText"
android:layout_marginTop="38dp"
android:onClick="buttonclick"
android:text="#string/enter" />
</RelativeLayout>
planets.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/planetTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/planet" />
<TextView
android:id="#+id/textViewform2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/mercuryRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/mercury" />
<RadioButton
android:id="#+id/venusRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/venus" />
<RadioButton
android:id="#+id/earthRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/earth" />
<RadioButton
android:id="#+id/marsRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/mars" />
<RadioButton
android:id="#+id/jupiterRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/jupiter" />
<RadioButton
android:id="#+id/saturnRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/saturn" />
<RadioButton
android:id="#+id/uranusRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/uranus" />
<RadioButton
android:id="#+id/neptuneRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/neptune" />
<RadioButton
android:id="#+id/plutoRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pluto" />
</RadioGroup>
<Button
android:id="#+id/selectButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonclick2"
android:text="#string/select" />
<TextView
android:id="#+id/textViewform2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
JAVA:
package com.deitel.planetaryweight;
import android.os.Bundle;
import android.app.Activity;
import android.widget.*;
import android.view.View;
import android.view.Menu;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
public class MainActivity extends Activity {
//Global variable
double weight;
private Button enter; // creates a button
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enter = (Button) findViewById(R.id.enterButton);
//Start with first screen
setContentView(R.layout.activity_main);
}
//buttonclick for form 1
public void buttonclick(View view){
//creates an editext and assigns the resource id of the xml edittext.
EditText wtentry = (EditText)findViewById(R.id.inputwtEditText);
//Receives the input from the edittext, converts it to a double (number).
weight = Double.parseDouble(wtentry.getText().toString());
//switch views to screen 2
setContentView(R.layout.planets);
//change the value of the textview on screen 2 to the calculation value
TextView t2 = (TextView)findViewById(R.id.textViewform2);
t2.setText(Double.toString(weight));
}
//buttonclick for form 2!
public void buttonclick2(View view){
setContentView(R.layout.planets);
RadioButton mercury = (RadioButton) findViewById(R.id.mercuryRadio);
RadioButton venus = (RadioButton) findViewById(R.id.venusRadio);
RadioButton earth = (RadioButton) findViewById(R.id.earthRadio);
RadioButton mars = (RadioButton) findViewById(R.id.marsRadio);
RadioButton jupiter = (RadioButton) findViewById(R.id.jupiterRadio);
RadioButton saturn = (RadioButton) findViewById(R.id.saturnRadio);
RadioButton uranus = (RadioButton) findViewById(R.id.uranusRadio);
RadioButton neptune = (RadioButton) findViewById(R.id.neptuneRadio);
RadioButton pluto = (RadioButton) findViewById(R.id.plutoRadio);
//Makes a variable for the entered amount
Double mercurypf;
Double venuspf;
Double earthpf;
Double marspf;
Double jupiterpf;
Double saturnpf;
Double uranuspf;
Double neptunepf;
Double plutopf;
Double weight;
// constants
final double mercuryforce = 0.38;
final double venusforce = 0.91;
final double earthforce = 1.00;
final double marsforce = 0.38;
final double jupiterforce = 2.34;
final double saturnforce = 1.06;
final double uranusforce = .92;
final double neptuneforce = 1.19;
final double plutoforce = 0.06;
// Code used to determine which planet RadioButton is checked:
if(mercury.isChecked())
{
mercurypf = mercuryforce * weight;
}
else
{
mercurypf = 0.00;
}
if(venus.isChecked())
{
venuspf = venusforce * weight;
}
else
{
venuspf = 0.00;
}
if(earth.isChecked())
{
earthpf = earthforce * weight;
}
else
{
earthpf = 0.00;
}
if(mars.isChecked())
{
marspf = marsforce * weight;
}
else
{
marspf = 0.00;
}
if(jupiter.isChecked())
{
jupiterpf =jupiterforce * weight;
}
else
{
jupiterpf = 0.00;
}
if(saturn.isChecked())
{
saturnpf = saturnforce * weight;
}
else
{
saturnpf = 0.00;
}
if(uranus.isChecked())
{
uranuspf = uranusforce * weight;
}
else
{
uranuspf = 0.00;
}
if(neptune.isChecked())
{
neptunepf = neptuneforce * weight;
}
else
{
neptunepf = 0.00;
}
if(pluto.isChecked())
{
plutopf = plutoforce * weight;
}
else
{
plutopf = 0.00;
}
}
}
One way to do it is:
Create a new class called say Constants and declare this variable as static there. Now you can access this variable from all you activities.
public class Constants {
public static double weight;
}
Access it from all your activities as
Constants.weight = 2.5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enter = (Button) findViewById(R.id.enterButton);
}
You should be setting the content view BEFORE you find any view.
Further, you don't need any changes in the way you've defined your variables, given weight is a private variable in your MainActivity class, and you're shifting views in the same activity. The variable is storing the value of the editText BEFORE you change the view so it won't lose the value in the same class even if you change the contentView. As far as I can see, the problem is that you're not setting the enter button right (the change I've suggested above should work).
In addition to the rest, there's some structural and design issues you need to resolve. Take a look at the docs for information on passing information back and forth to and from Activities. setContentView() shouldn't be called more than once in an Activity unless you have a good reason to.
public class MainActivity extends Activity {
/* You should get used to declaring everything with the correct visibility. Good practice is to make everything private and use public mutator methods */
//Global variable
private double weight;
private Button enter; // creates a button
// Views
private EditText wtEntry;
private TextView txtForm2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Start with first screen
setContentView(R.layout.activity_main);
enter = (Button) findViewById(R.id.enterButton);
//creates an editext and assigns the resource id of the xml edittext.
wtEntry = (EditText)findViewById(R.id.inputwtEditText);
txtForm2 = (TextView)findViewById(R.id.textViewform2);
}
// Button clicks shouldn't do anything but perform clicky actions. Leave field initialization, view creation, etc to the Activity.
//buttonclick for form 1
public void buttonclick(View view){
//Receives the input from the edittext, converts it to a double (number).
weight = Double.parseDouble(wtEntry.getText().toString());
//change the value of the textview on screen 2 to the calculation value
t2.setText(Double.toString(weight));
// If you want a new layout, it's best to start a new activity.
// It looks like you want to get information back, so use startActivityForResult().
// setContentView(R.layout.planets);
Intent dataIntent = new Intent(this, PlanetChooser.class);
dataIntent.putExtra("com.yourpackage.identifier.DATA_WEIGHT", weight);
startActivityForResult(dataIntent, Activity.RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check that the resultCode is the same as we started the activity with
if(resultCode == Activity.RESULT_OK){
// get the double from the Intent, using the same string name (package prefixed)
// or a default value if it didn't get set.
double resultWeight = data.getDoubleExtra("com.yourpackage.identifier.RESULT_WEIGHT", 0.0);
// Now do something with resultWeight
}
}
}
// PlanetChooser.class
public class PlanetChooser extends Activity {
// constants, usually denoted by uppercase and declared static and final
public static final double MERCURYFORCE = 0.38;
public static final double VENUSFORCE = 0.91;
public static final double EARTHFORCE = 1.00;
public static final double MARSFORCE = 0.38;
public static final double JUPITERFORCE = 2.34;
public static final double SATURNFORCE = 1.06;
public static final double URANUSFORCE = 0.92;
public static final double NEPTUNEFORCE = 1.19;
public static final double PLUTOFORCE = 0.06;
private RadioButton mercury, venus, earth, mars, jupiter, saturn, uranus, neptune, pluto;
// No need to use the Double object as opposed to the primitive unless you have good reason
private double mercurypf, venuspf, earthpf, marspf, jupiterpf, saturnpf, uranuspf, neptunepf, plutopf, weight;
// One variable will suffice, it seems.
private double resultForce;
public void onCreate(Bundle s){
super.onCreate(s);
setContentView(R.layout.planets);
mercury = (RadioButton) findViewById(R.id.mercuryRadio);
venus = (RadioButton) findViewById(R.id.venusRadio);
earth = (RadioButton) findViewById(R.id.earthRadio);
mars = (RadioButton) findViewById(R.id.marsRadio);
jupiter = (RadioButton) findViewById(R.id.jupiterRadio);
saturn = (RadioButton) findViewById(R.id.saturnRadio);
uranus = (RadioButton) findViewById(R.id.uranusRadio);
neptune = (RadioButton) findViewById(R.id.neptuneRadio);
pluto = (RadioButton) findViewById(R.id.plutoRadio);
}
public void buttonclick2(View view){
/*
It looks to me here you're looking to see which box is checked, and set a value based on
that planet. Since instance variables (in this case mercurypf, jupiterpf, etc) are initialized
to the default value (0), there's no need to set them manually.
*/
// Code used to determine which planet RadioButton is checked:
if(mercury.isChecked()) {
resultForce = MERCURYFORCE * weight;
}
if(venus.isChecked()){
resultForce = VENUSFORCE * weight;
}
if(earth.isChecked()){
resultForce = EARTHFORCE * weight;
}
if(mars.isChecked()){
resultForce = MARSFORCE * weight;
}
if(jupiter.isChecked()){
resultForce =JUPITERFORCE * weight;
}
if(saturn.isChecked()){
resultForce = SATURNFORCE * weight;
}
if(uranus.isChecked()){
resultForce = URANUSFORCE * weight;
}
if(neptune.isChecked()){
resultForce = NEPTUNEFORCE * weight;
}
if(pluto.isChecked()){
resultForce = PLUTOFORCE * weight;
}
// Create a new data Intent to pass back to the calling activity, set the result code,
// and manually finish() this activity.
Intent dataIntent = new Intent(this);
dataIntent.putDoubleExtra("com.yourpackage.identifier.RESULT_DATA", resultForce);
setResult(Activity.RESULT_OK, dataIntent);
finish();
}
}
Use Application or static variable to save the value globally. see the example
Create a new class that extends Application.
public class Globals extends Application{
private int data=200;
public int getData(){
return this.data;
}
public void setData(int d){
this.data=d;
}
}
Second:
Add the class to the AndroidManifest file as an attribute of <application> tag:
<application android:name=".Globals" />
Then you can access your global data from any Activity by calling getApplication()
Globals g = (Globals)getApplication();
int data=g.getData();
Static Variable Example
class Global{
public static int global=1;
}
in your activity simply use it with its class name
int a;
a=Global.global;

Scrolling ListViews Together

I've got two ListView objects that I would like to scroll together. They are side-by-side, so if one scrolls a certain amount, the other scrolls that same amount. I've found some examples on how to do this, but I believe that they rely on the items in the ListView being the same height (correct me if I am wrong). The items in one of my ListView objects are taller than the ones in the other, spanning 2-3 items.
How do I "lock" these 2 ListView objects together?
EDIT: Here's a screenshot of what I have, maybe it will better explain what I'm going for. The left side (red) is a list of items and the right side is a separate list. You can see how the lists don't align perfectly, so it isn't exactly a grid. What I would like to do is have this act like one big list, where scrolling either list will also scroll the other.
I created a rough class that does basically what I wanted to do. It's not smart enough to handle if the 2nd list is longer than the 1st or if the orientation changes, but it's good enough to get the concept down.
To set it up:
list1.setOnScrollListener(new SyncedScrollListener(list2));
list2.setOnScrollListener(new SyncedScrollListener(list1));
SyncedScrollListener.java
package com.xorbix.util;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
public class SyncedScrollListener implements OnScrollListener{
int offset;
int oldVisibleItem = -1;
int currentHeight;
int prevHeight;
private View mSyncedView;
public SyncedScrollListener(View syncedView){
if(syncedView == null){
throw new IllegalArgumentException("syncedView is null");
}
mSyncedView = syncedView;
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int[] location = new int[2];
if(visibleItemCount == 0){
return;
}
if(oldVisibleItem != firstVisibleItem){
if(oldVisibleItem < firstVisibleItem){
prevHeight = currentHeight;
currentHeight = view.getChildAt(0).getHeight();
offset += prevHeight;
}else{
currentHeight = view.getChildAt(0).getHeight();
View prevView;
if((prevView = view.getChildAt(firstVisibleItem - 1)) != null){
prevHeight = prevView.getHeight();
}else{
prevHeight = 0;
}
offset -= currentHeight;
}
oldVisibleItem = firstVisibleItem;
}
view.getLocationOnScreen(location);
int listContainerPosition = location[1];
view.getChildAt(0).getLocationOnScreen(location);
int currentLocation = location[1];
int blah = listContainerPosition - currentLocation + offset;
mSyncedView.scrollTo(0, blah);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
}
I think it is more appropriate to use a GridView with 2 columns, something like this:
<GridView
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="2"
/>
What I would like to do is to listen to the scrolling event for the left listview and then scroll the right listview by an proper offset. Below is my code, I tested it(very simple, just show you my thought) and you may add your code based on it.
package viewTest.example.hy;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
public class ViewTestActivity extends Activity {
private ArrayAdapter<String> adapter0;
private ArrayAdapter<String> adapter1;
private String[] array0;
private String[] array1;
private ListView lv0;
private ListView lv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array0 = getResources().getStringArray(R.array.LV0);//letters from A to O
array1 = getResources().getStringArray(R.array.LV1);//numbers from 1 to 14
adapter0 = new ArrayAdapter<String>(this, R.layout.item, array0);
adapter1 = new ArrayAdapter<String>(this, R.layout.item, array1);
lv0 = (ListView) findViewById(R.id.listView1);
lv1 = (ListView) findViewById(R.id.listView2);
lv0.setAdapter(adapter0);
lv1.setAdapter(adapter1);
lv0.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
lv1.setSelection(firstVisibleItem);//force the right listview to scrollyou may have to do some calculation to sync the scrolling status of the two listview.
}
});
}
}
And this is the main.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="none">
</ListView>
<ListView
android:id="#+id/listView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="none" >
</ListView>
</LinearLayout>
Here is my screenshot:
I ended up using the top s/o answer here: Android. Scrolling 2 listviews together
Intercepting and redirecting events seems to be a lot more elegant and consistent than trying to do my own math on the dimensions and state of the listviews.

Categories

Resources