I am creating a times tables app, in which one of the activities allows the user to enter which times tables they would like to view, then the app will bring up that times tables.(e.g. 6x5=30) etc.
Below is the xml layout I have created for the activity:
<?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"
android:padding="15dp">
<TextView
android:id="#+id/tvTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I want to see the: "
android:textSize="25dp" />
<EditText
android:id="#+id/etEnterNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Number..."
>
</EditText>
<TextView
android:id="#+id/tvBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Times tables!"
android:textSize="25dp" />
<Button
android:id="#+id/btnGo"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="Go"
android:layout_gravity="center"/>r
</LinearLayout>
And this it the java class I have created thus far for the classes functionalitiy:
public class ViewTimesTables extends Activity implements View.OnClickListener {
// Declaring Vars
Button go;
EditText enterNumber;
TextView top;
TextView bottom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting equal to text layout View
setContentView(R.layout.view);
// calling method to intialise vars
initialiseVars();
}// on create end
/**
* method to initialise all of the buttons, textviews etc used to clean up
* the onCreate.
*/
private void initialiseVars() {
// Setting up (initialising) all the buttons text views etc from the xml
// (vid 25)
go = (Button) findViewById(R.id.btnGo);
enterNumber = (EditText) findViewById(R.id.etEnterNumber);
top = (TextView) findViewById(R.id.tvTop);
bottom = (TextView) findViewById(R.id.tvBottom);
}
/**
* Method with on click listener that adds functionality for all of the
* buttons, text views etc
*
* #param v
*/
public void onClick(View view) {
// switch statement which determines what is clicked
switch ((view).getId()) {
case R.id.etEnterNumber:
// code to read user number (i.e. between 1 and 12)
//And possibly link to go button
break;
case R.id.btnGo:
// code to bring up new activity/screen with times table
// of the number that was entered in edit text
break;
}
}
}
I am unsure how to add the correct functionality (probably within switch statement) so that when e.g. "6" is entered in the edit text box and the "go" button is pressed then the 6 times tables will be brought up in a new activity?
I would begin by looking at Intents to start a new activity and pass data to it.
A relevant tutorial is this Android Intents Tutorial
Getting the text from a edit text is a simple as enterNumber.getText().getString()
You could then use a conditional statement to call the designated class.
Something like this would allow you to pass two values to the SixTimesTables class with the values 5 and 6 passed in.
if(enterNumber.getText().getString().equals("6")){
Intent i = new Intent(this, SixTimesTables.class);
i.putExtra("Value1", 5);
i.putExtra("Value2", 6);
// set the request code to any code you like,
// you can identify the callback via this code
startActivityForResult(i, REQUEST_CODE);
}
You probably want a dynamic layout for next activity.
It may help you.
http://www.dreamincode.net/forums/topic/130521-android-part-iii-dynamic-layouts/
Then you can switch between activities as AndyGable mentioned.
Hopefully it'll help you.
You really dont need the onClick for the editText you can handle if data is entered in the editText or not from the button click only like this:
public void onClick(View view) {
// switch statement which determines what is clicked
switch ((view).getId()) {
case R.id.btnGo:
// code to bring up new activity/screen with times table
// of the number that was entered in edit text
// check if editText has values or not
if(TextUtils.isEmpty(mEditText.getText().toString())) {
mEditText.setError("Please enter a number");
}else {
int number = Integer.parseInt(mEditText.getText().toString());
Intent intent = new Intent(YourCurrentActivity.this, NextActivity.class);
intent.putExtra("value", number);
startActivity(intent);
// it is always good to check if the value entered is a number only or not
// add inputType tag in the xml
// android:inputType="number" for the editText.
}
break;
}
}
Now, in order to get value in the next activity do this:
// write this inside the onCreate of the Activity.
int number;
if(getIntent().getExtras() != null) {
number = getIntent().getIntExtra("value");
}
// use the number then to display the tables
Related
I would like to enable or disable the OK (POSITIVE) button of the AlertDialog with a custom layout such that I can:
Disable the OK button initially
Enable the OK button when all required fields have been entered
Disable the OK button again if a required field has been cleared
Perform validation after the OK button is selected and prevent dismissal upon validation errors
Assume the AlertDialog layout is as follows with one required field description and one optional field age:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditText
android:id="#+id/description"
android:hint="Field is required"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/age" />
<EditText
android:id="#+id/age"
android:hint="Optional"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/description"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Assume I have a button to kick off the dialog
Button b = findViewById(R.id.main_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG,"button");
View viewcustom = getLayoutInflater().inflate(R.layout.customdialog,null);
EditText edt1 = viewcustom.findViewById(R.id.description);
EditText edt2 = viewcustom.findViewById(R.id.age);
// render alertdialog
}
});
Here is the code. I created a custom layout with 2 EditText fields and require only 1 to be entered. The first is treated as just text that must be present and the second is treated as an optional Age. The final example shows how to add validation and to "not dismiss" after OK is pressed and validation fails.
The OK button is initially disabled and when data is entered in the first text field the OK button is enabled.
By controlling the enable/disable of the positive (OK) button it requires the user to the enter fields necessary (rather than giving them an error when omitted).
Note that when the user clears the same field the OK button is disabled.
You can also add a hint to the EditText field(s) to indicate required (shown in second example).
Note that this was used as reference for the EditText listening (as I linked to in comment).
Finally, the last demo shows if you really wanted to show an error on field validation after the OK button is enabled and pressed. (From here.)
This should be obvious how to expand it to all your EditText fields. And bear in mind you can an condition to enabling the OK button - here it is just at least one character.
Button b = findViewById(R.id.main_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e(TAG,"button");
View viewcustom = getLayoutInflater().inflate(R.layout.customdialog,null);
EditText edt1 = viewcustom.findViewById(R.id.description);
EditText edt2 = viewcustom.findViewById(R.id.age);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this)
.setView(viewcustom)
.setPositiveButton("Ok", (dialogInterface, i) -> {
String d = edt1.getText().toString();
String a = edt2.getText().toString();
Toast.makeText(MainActivity.this,d, Toast.LENGTH_LONG).show();
});
alertDialog.setNegativeButton("Cancel", null);
AlertDialog ad = alertDialog.create();
edt1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence sequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence sequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
if (edt1.getText().length() > 0) {
// if user enters anything then enable - modify criteria as desired
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(true);
} else {
// if user deletes entry then back to disabled
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
}
});
// Initially OK button is disabled.
ad.show();
ad.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
}
});
And demo:
You can also add a hint to each field to indicate it is required if nothing is entered as in :
<EditText
android:id="#+id/description"
android:hint="Field is required"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="#id/age" />
Finally, if you really, really want to allow the OK but then do further validation to display errors then add the following. Note that the second field is treated as an Age field and the data entered must be an integer. A bit contrived but used to show an example.
// add this after the AlertDialog create()
ad.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface anInterface) {
Button b = ad.getButton(DialogInterface.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do some validation on edit text
String s = edt2.getText().toString();
try {
Integer age = Integer.valueOf(s);
Toast.makeText(MainActivity.this,d+":"+age, Toast.LENGTH_LONG).show();
ad.dismiss();
} catch (Exception e) {
// complain
Toast.makeText(MainActivity.this, "Age must be an integer", Toast.LENGTH_LONG).show();
}
}
});
}
});
And demo of requiring the optional Age to be an integer:
I am creating an app in Android where I have a button that displays silly phrases when pressed. I figured out how to get it to say two phrases but I can't figure out how to make it do more. I also want to add in a feature to have the button pick phrases at random instead of going in the order I set. I am thinking of using an arraylist for this. How do I set the button to cycle through different methods in Andrido Studio?
I also want you to know that I am a beginner so please don't be too hard on me.
This is my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/funny_imageview"
android:scaleType="fitCenter" />
<TextView
android:id="#+id/funny_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text=""/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/funny_sayings_button"
android:text="Click Me!"
android:layout_marginTop="8dp"
android:onClick="changeFunnySayingsButton"/>
</LinearLayout>
This is my Java:
package com.example.android.funnysayingsbutton;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
boolean clicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method changes the funny text and image on the screen when the button is clicked.
*/
public void changeFunnySayingsButton (View view){
if (clicked){
funnySayingOne();
clicked = false;
}
else {
funnySayingTwo();
clicked = true;
}
}
/**
* This method is for the first funny expression.
*/
public void funnySayingOne(){
displayAnswer("Time to Monkey Around");
displayImage(R.drawable.monkey);
}
/**
* This method is for the second funny expression.
*/
public void funnySayingTwo(){
displayAnswer("Penguin Party Time");
displayImage(R.drawable.penguin);
}
/**
* This method is for the third funny expression.
*/
public void funnySayingThree(){
displayAnswer("It's Rabbit Season.");
displayImage(R.drawable.rabbit);
}
/**
* This method displays the funny text on the screen.
*/
private void displayAnswer(String answer) {
TextView questionTextView = (TextView) findViewById(R.id.funny_textview);
questionTextView.setText(answer);
}
/**
* This method displays the funny image on the screen.
*/
private void displayImage(int picture) {
ImageView questionTextView = (ImageView) findViewById(R.id.funny_imageview);
questionTextView.setImageResource(picture);
}
}
I think that you're on the right track thinking about using a data structure like an ArrayList.
I'd start by making a class to represent each funny thing, e.g.
public class FunnyThing {
private String phrase; // I'd use a resource ID here
private int drawableResourceId;
}
Then it's a matter of initializing the set of FunnyThing objects and storing them in your data structure. You could do this in the onCreate method of your activity, but you may want to consider writing a factory method somewhere else (e.g. the FunnyThing class) that your activity just calls to keep the code from getting cluttered when there are more than 2-3 funny things.
Finally, on each button press you can choose a random index in your collection of FunnyThings and display that, e.g.
private void displayRandomFunnyThing() {
// assumes you have a java.util.Random instance vairable named mRandom
FunnyThing ft = mFunnyThings.get( mRandom.nextInt( mFunnyThings.size());
displayAnswer( ft.phrase );
displayImage( ft.drawableResourceId);
}
Of course you'll need to add an onClickListener to your button, but I'm assuming that you left that code out for brevity.
You'll also have the problem that the phrase selection is random, so you may get the same phrase many times before you see all of them. If you want to prevent duplicates, well, that will take more code.
First of all, where is your button onClick listener? This is where you should add your methods.
Button button = (Button)this.findViewById(R.id.funny_sayings_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeFunnySayingsButton (v);
}
});
To continue with you could create an ArrayList of Strings. You add all of your strings and then simply pick one at random from the list. Hint:
//will choose a random number between 0 and the length of the list - 1
int i = rand.nextInt(yourList.size());
String yourFunnyString=yourList.get(i);
If you also want to display an image alongside with the String you should also create a map. Use the String as a key. When you select from yourList then use this key to select the value (your image) from the map.
It should be fairly straightforward to do.
I have a program that handles song objects with some fields and playlist objects that are arrays of the songs. I have a perfectly functioning java programming that does what I need it to do but I'm trying to convert it into an Android app and it's making me want to throw my computer out the window. I don't really know XML but I've gotten the basics such as creating buttons etc.
I have a button in the layout file that I implemented as follows:
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/Button"
android:onClick="newPlaylist"/>
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1" />
In my main file I have:
public void newPlaylist(View view){
Playlist list1 = new Playlist("First Playlist");
TextView first = (TextView) findViewById(R.id.textView1);
first.setText(list1.getName());
}
Edit: I was able to add a little to the newPlaylist method. Now when I click the button it displays the name of the playlist, but I still want to edit it and be able to have multiple playlists on the screen to manipulate.
All I want to do is display the playlist name as either a text or label that is clickable so that the name can be changed and I can move on from here.
The Android documentation on the button component might help you with your problem.
I assume that your Playlist class looks something like this
public class Playlist {
private String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
If it does, then your method for handling the button click should look like this.
public void newPlaylist(View view) {
Playlist playlist = new Playlist("My First Playlist!"); // Create our playlist object
// Since button is the only component that uses 'newPlaylist' as a click listener, the view will always be the button
Button button = (Button) view; // We cast the view to button
button.setText(playlist.getName()); // This edits the button text, might want to create a TextView for this
}
I have the following layout defined in useful_numbers_item_fragment.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/call_linear_layout">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/useful_nums_item_name"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/useful_nums_item_value"/>
</LinearLayout>
<ImageButton
android:layout_width="0dp"
android:layout_height="wrap_content"
android:src="#drawable/call"
android:id="#+id/call_btn"
android:onClick="callNumber"/>
</LinearLayout>
I dynamically populate the two text views in a class called UNItemListFragment.java
in the onCreate method:
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
if (getArguments().containsKey(Constants.UNItem.GROUP_ID)) {
simpleCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.useful_numbers_item_fragment, null,
new String[]{Constants.UNItem.NAME, Constants.UNItem.VALUE},
new int[]{R.id.useful_nums_item_name, R.id.useful_nums_item_value}, 0);
setListAdapter(simpleCursorAdapter);
getLoaderManager().initLoader(0, getArguments(), this);
}
}
For each number if i click on the button i want to make a phone call by
calling the callNumber method when the user clicks the button:
public void callNumber(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
TextView unItemVal = (TextView) findViewById(R.id.useful_nums_item_value);
String phoneNumber = unItemVal.getText().toString();
callIntent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(callIntent);
}
It is ok when I click the first button in the list, but when I click on the other buttons
it continues calling the number defined in the first row...
Any idea how to resolve this?
The problem is that this line:
TextView unItemVal = (TextView) findViewById(R.id.useful_nums_item_value);
is executed on the activity, so the findViewById will always return the first item with that id, which is likely the first item in the list.
The best way to fix this would be to override the adapter and add a tag containing the phone number to the view. A quick way to fix this would be to tag along in the view hierarchy, like so:
public void callNumber(View view) {
if( view != null ) { // view is the button tapped
View parent = view.getParent(); // this should be the LinearLayout
if( parent instanceof LinearLayout ) {
TextView unItemVal = (TextView) ((LinearLayout)parent).findViewById(R.id.useful_nums_item_value);
if( unItemVal != null ) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phoneNumber = unItemVal.getText().toString();
callIntent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(callIntent);
}
}
}
}
This would find the parent for the button that was clicked, and then find the text-view containing the number within that ViewGroup.
Using findViewById() will return the first view in the activity or fragment with the specified id. If this is a ListView, it will correspond to the first row.
There are many ways to work around this problem. The quickest one (but certainly not the prettiest one, since it depends on the layout) would be to use findViewById() relative to the LinearLayout that contains the list item. Assuming that view is the ImageButton, it would be somthing like:
((View)view.getParent()).findViewById(R.id.useful_nums_item_value)
A more elegant solution would be to set a tag in the adapter's getView(), containing the data you need (in this case, the phone number to call).
I uploaded my app yesterday to Google Play and this morning I've wanted to make just a layout tweak as some of the text was overlapping buttons on smaller screens, basically I just want to move the buttons further down the screen. I thought this would be as easy as using eclipse's graphical editor... Nope.
I have no idea why but the small edit I've done to the position of the buttons on my "view_fact" layout has registered the buttons with the wrong OnClick listeners, there's only two buttons on the view and they're using eachothers event listeners and I have no idea why. I didn't touch the event listener code that was working perfectly on the old layout.
Here is my view_fact layout:
<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/viewFactTitleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/factTitleText"
android:textSize="22dp"
tools:context=".MainActivity" />
<ImageView
android:id="#+id/randomFactImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/viewFactTitleText"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:contentDescription="Fact Image"
android:src="#drawable/canadaflag" />
<TextView
android:id="#+id/factData"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#+id/randomFactImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="TextView" />
<Button
android:id="#+id/anotherFactButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/backToHomeButton"
android:layout_alignLeft="#+id/backToHomeButton"
android:layout_alignRight="#+id/backToHomeButton"
android:text="#string/anotherFactButtonText" />
<Button
android:id="#+id/backToHomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/factData"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/factData"
android:text="#string/backToHomeButtonText" />
</RelativeLayout>
Listener and startup code:
public class MainActivity extends Activity {
/* Declaration of global variables */
private boolean debugMode = true; // Whether debugging is enabled or not
private static String logtag = "CanadianFacts"; // For use as the tag when logging
private TextView factData;
private int totalFacts = 72;
private String[][] facts = new String[totalFacts][5];
private int lastFact = 0;
/* Buttons */
/* Home page */
private Button randomFactButton;
/* View Fact page */
private Button anotherRandomFactButton;
private Button backToHomeButton;
/* About page */
private Button backToHomeFromAboutButton;
/* Image Views */
private ImageView randomFactImage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Home Page Objects */
randomFactButton = (Button)findViewById(R.id.randomFactButton);
randomFactButton.setOnClickListener(randomFactListener); // Register the onClick listener with the implementation above
/* View Fact Page Objects */
/* Build Up Fact Array */
buildFactArray();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
loadAboutPage(); // Call the loadAboutPage method
return true;
}
return false;
}
public void loadAboutPage() {
setContentView(R.layout.about);
/* Set up home page button listener */
backToHomeFromAboutButton = (Button)findViewById(R.id.backToHomeFromAboutButton);
backToHomeFromAboutButton.setOnClickListener(backToHomeListener); // We can reuse the backToHomeListener
}
/* Home Page Listeners */
//Create an anonymous implementation of OnClickListener, this needs to be done for each button, a new listener is created with an onClick method
private OnClickListener randomFactListener = new OnClickListener() {
public void onClick(View v) {
if (debugMode) {
Log.d(logtag,"onClick() called - randomFact button");
Toast.makeText(MainActivity.this, "The random fact button was clicked.", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.view_fact); // Load the view fact page
/* We're now on the View Fact page, so elements on the page are now in our scope, instantiate them */
/* Another Random Fact Button */
anotherRandomFactButton = (Button)findViewById(R.id.anotherFactButton);
anotherRandomFactButton.setOnClickListener(anotherRandomFactListener); // Register the onClick listener with the implementation above
/* Back to Home Button */
backToHomeButton = (Button)findViewById(R.id.backToHomeButton);
backToHomeButton.setOnClickListener(backToHomeListener); // Register the onClick listener with the implementation above
// Get a random fact
String[] fact = getRandomFact();
if (fact[2] == null) { // If this fact doesn't have an image associated with it
fact[2] = getRandomImage();
}
int imageID = getDrawable(MainActivity.this, fact[2]);
/* See if this fact has an image available, if it doesn't select a random generic image */
randomFactImage = (ImageView) findViewById(R.id.randomFactImage);
randomFactImage.setImageResource(imageID);
factData = (TextView) findViewById(R.id.factData);
factData.setText(fact[1]);
if (debugMode) {
Log.d(logtag,"onClick() ended - randomFact button");
}
}
};
/* View Fact Page Listeners */
private OnClickListener anotherRandomFactListener = new OnClickListener() {
public void onClick(View v) {
if (debugMode) {
Log.d(logtag,"onClick() called - anotherRandomFact button");
Toast.makeText(MainActivity.this, "The another random fact button was clicked.", Toast.LENGTH_LONG).show();
}
// Get a random fact
String[] fact = getRandomFact();
if (fact[2] == null) { // If this fact doesn't have an image associated with it
fact[2] = getRandomImage();
}
int imageID = getDrawable(MainActivity.this, fact[2]); // Get the ID of the image
/* See if this fact has an image available, if it doesn't select a random generic image */
randomFactImage = (ImageView) findViewById(R.id.randomFactImage);
randomFactImage.setImageResource(imageID);
factData = (TextView) findViewById(R.id.factData);
factData.setText(fact[1]);
if (debugMode) {
Log.d(logtag,"onClick() ended - anotherRandomFact button");
}
}
};
private OnClickListener backToHomeListener = new OnClickListener() {
public void onClick(View v) {
if (debugMode) {
Log.d(logtag,"onClick() called - backToHome button");
Toast.makeText(MainActivity.this, "The back to home button was clicked.", Toast.LENGTH_LONG).show();
}
// Set content view back to the home page
setContentView(R.layout.main); // Load the home page
/* Reinstantiate home page buttons and listeners */
randomFactButton = (Button)findViewById(R.id.randomFactButton);
randomFactButton.setOnClickListener(randomFactListener); // Register the onClick listener with the implementation above
if (debugMode) {
Log.d(logtag,"onClick() ended - backToHome button");
}
}
};
Thank you.
I've managed to fix this, by moving the buttons around, changing the IDs a few times and then changing them back. And removing all of the align settings and resetting it's position.
A very strange problem, probably due to eclipse's graphical editor.