i am trying to get my buttons to change to a diffrent pic and a dif set of laws
it is an alphabet app that i currently have working and its on the market.... i want to make it randomly change the pic and then follow the alphebet through the whole program but i cant figure out how to get the buttons to randomize so here is the basic code that i am using
package com.alphafree;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class letterA extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int[] _26Num = new int[6];
int i, number;
Random r1 = new Random(); // Random generator
for (i = 1; i < _26Num.length; i++) { // Pick 6 Random Numbers
do {
number = (int) (r1.nextDouble() * 26);
_26Num[1] = 1;
} while (!(number != 0 && number != _26Num[1]
&& number != _26Num[2] && number != _26Num[3]
&& number != _26Num[4] && number != _26Num[5]));
_26Num[i] = number;
}
// defines the buttons
View but1 = findViewById(R.id.let1);
View but2 = findViewById(R.id.let2);
View but3 = findViewById(R.id.let3);
View but4 = findViewById(R.id.let4);
View but5 = findViewById(R.id.let5);
but1.setOnClickListener(this);
but2.setOnClickListener(this);
but3.setOnClickListener(this);
but4.setOnClickListener(this);
but5.setOnClickListener(this);
// set the random content view
int random = (int) Math.ceil(Math.random() * 5);
if (random == 1) {
setContentView(R.layout.letter1a);
} else if (random == 2) {
setContentView(R.layout.letter1a);
} else if (random == 3) {
setContentView(R.layout.letter1a);
} else if (random == 4) {
setContentView(R.layout.letter1a);
} else if (random == 5) {
setContentView(R.layout.letter1a);
}
// here is were i need to set up the buttons
if (_26Num[1] == 1) {
let1.setBackgroundResource(R.drawable.let_a);
} else if (_26Num[1] == 2) {
setContentView(R.layout.letter1a);
}
}
public void onClick(View v) {
if (mp != null)
mp.release();
switch (v.getId()) {
case R.id.let1:
mp = MediaPlayer.create(this, R.raw.correct);
{
new AlertDialog.Builder(this)
.setTitle("Y A Y!!!! Y O U R R I G H T")
.setMessage(
"Thats the letter 'A' You Chose Correct")
.setNeutralButton("Done", null).show();
startActivity(new Intent("com.alphafree.LETTERB"));
}
break;
}
mp.seekTo(0);
mp.start();
}
}
You could do it about that way:
private static final int[] num2DrawableMap = new int[] {
R.drawable.letterA,
R.drawable.letterB,
// etc
};
private static final int[] num2LayoutMap = new int[] {
R.layout.layoutA,
R.layout.layoutB,
// etc
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int[] _26Num = new int[6];
int i, number;
Random r1 = new Random(); // Random generator
for (i = 1; i < _26Num.length; i++) { // Pick 6 Random Numbers
do {
// don't you like r1.nextInt(26) ?
number = (int) (r1.nextDouble() * 26);
// always 1? why in that loop?
_26Num[1] = 1;
} while (!(number != 0 && number != _26Num[1]
&& number != _26Num[2] && number != _26Num[3]
&& number != _26Num[4] && number != _26Num[5]));
_26Num[i] = number;
}
// set the random content view
int random = r1.nextInt(num2LayoutMap.size);
setContentView(num2LayoutMap[random]);
// find the buttons
View[] buts = new View[5];
buts[0] = findViewById(R.id.let1);
buts[1] = findViewById(R.id.let2);
buts[2] = findViewById(R.id.let3);
buts[3] = findViewById(R.id.let4);
buts[4] = findViewById(R.id.let5);
for (View but : buts) {
but.setOnClickListener(this);
int drawableId = num2DrawableMap[_26Num[i]];
but.setBackgroundResource(drawableId);
}
}
But: the Buttons have to be inside every of your layout.xml files and they need to have the same id. Otherwise you don't find them. Also you need to setContentView() before you can use findViewById()
Other than setContentView every time, Can you add all at a time and keep their visibility to GONE. what ever the button you want to display just make its visibility to VISIBLE. If you want to change make the Previous to GONE and make the new one VISIBLE.
Related
I have this code below, my adapter and my LayoutManager (Grid) are set above this code, but the values returned by
findLastCompletelyVisibleItemPosition
are sometimes wrong (returns 1 instead of 5 for example)
I think this method is little bugged,
how can i get the good values ?
holder.mRecyclerViewImage.postDelayed(new Runnable() {
#Override
public void run() {
if (holder.mLastVisibleItems == -1)
holder.mLastVisibleItems = holder.mGridLayoutManager.findLastCompletelyVisibleItemPosition();
Log.d("myItemPosition", holder.mLastVisibleItems + "");
if (holder.mLastVisibleItems == 0 || holder.mLastVisibleItems == -1)
return;
int deleted = 0;
ArrayList<String> saveList = new ArrayList<>(listUrlImg);
while (holder.mLastVisibleItems + 1 < listUrlImg.size()) {
listUrlImg.remove(holder.mLastVisibleItems + 1);
deleted++;
}
holder.mRecyclerViewImage.setAdapter(new ImageAdapter(saveList, listUrlImg, deleted));
}
}, 100);
How can I get to iterate through this ArrayList algorithm so that I can change the background of an imageView every time I input a code... E.g. Code = "123456" | Background_1 shows, Code = "123456" | Background_2 shows ...
enter = (ImageButton) findViewById(R.id.enter);
input = (EditText) findViewById(R.id.editText2);
punch_back_1 = (ImageView) findViewById(R.id.imageView6);
punch_back_2 = (ImageView) findViewById(R.id.imageView7);
punch_back_3 = (ImageView) findViewById(R.id.imageView8);
punch_back_4 = (ImageView) findViewById(R.id.imageView9);
final ArrayList<ImageView> array_image = new ArrayList<>();
array_image.add(punch_back_1);
array_image.add(punch_back_2);
array_image.add(punch_back_3);
array_image.add(punch_back_4);
enter.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
String code = input.getText().toString();
int i = 0;
if (code.equals("123456")) {
i++;
array_image.get(i).setImageResource(R.drawable.punch_front);
Toast.makeText(getApplication(), "Awarded 1 new punch", Toast.LENGTH_LONG).show();
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
input.setText(" ");
}
return false;
}
});
I've tried this both:
for (int i = 0; i < 4; i++)
{
if (code.equals("123456"))
{
array_image.get(i).setImageResource(R.drawable.punch_front);
Toast.makeText(getApplication(), "Awarded 1 new punch", Toast.LENGTH_LONG).show();
}
}
int i = 0;
while (i < i)
{
array_image.get(i).setImageResource(R.drawable.punch_front);
Toast.makeText(getApplication(), "Awarded 1 new punch", Toast.LENGTH_LONG).show();
i++;
}
Which, if I am not mistaken does the same thing.
The below line of code eventually worked for me. onTouch Action_UP was my culprit. Using input.setText(null); did the same effect I wanted and preserved my sanity...
enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = input.getText().toString();
if (code.equals("123456") && index < array_image.size()) {
array_image.get(index).setImageResource(R.drawable.punch_front);
index++;
Toast.makeText(getApplication(), "Awarded " + index + " new punch", Toast.LENGTH_LONG).show();
input.setText(null);
}
}
});
EDIT: I seem to have misunderstood your question. It looks as if you want to have the image appear only once per fire event.
Doing this would require you do two things.
Keep count of the index at which you'll be changing.
Increment the index after use.
Also, you'll need to insure you do not go out of bounds as well of course.
First create a counter for the index as a member.
private int index = 0;
Next you'll want to do what you were doing before almost. In your event listener:
if(code.equals("123456") && index < array_image.size())
{
array_image.get(index).setImageResource(R.drawable.punch_front);
index++;
}
This should keep track of the current index, increment its position for the next event, and after you've gone through your items in the array, it shouldn't give you any exception errors when you go out of bounds and try to fire the event again.
I'm trying to build a calculator that subtracts one textview from another. One of the textview has a constant value 5. The other textview gets its value after a user presses buttons from 0 to 9. There's also a button for a decimal sign (dot). So, for example, if I press buttons 4, 5, ., 6 and 7, the textview will show 45.67 and a third textview will present the answer (40.67).
This example works fine. But my problem is that I want to limit the number of integers (numbers before the dot) to three. Although I can do this by simply adding setMaximumIntegerDigits to 3, it doesn't work as I'd like. For example, if I press 4, 5 and 3, the textview shows 453. That's fine. However, if I then press another number, for example 7, it shows 537. If I press 8 after that, it shows 378, and so on.
The same problem doesn't exist for decimal numbers. So, my question is, how can I set the actual integer limit so that when I press a number for the fourth time, the application wouldn't change the number in textview?
The code:
public class MainActivity extends AppCompatActivity {
private TextView textResult;
private TextView textSubtractor;
private TextView textSubtractee;
private String display = "0";
private String result = "0";
private SharedPreferences mPrefs;
Button btnDone;
double num1, num2, sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult = (TextView) findViewById(R.id.textResult);
textSubtractor = (TextView) findViewById(R.id.textSubtractor);
textSubtractee = (TextView) findViewById(R.id.textSubtractee);
btnDone = (Button) findViewById(R.id.btnDone);
textSubtractor.setText(display);
textResult.setText(result);
mPrefs = getSharedPreferences("test", 0);
if (mPrefs != null){
display = mPrefs.getString("display", "0");
sub = mPrefs.getInt(result, 0);
}
updateScreen();
btnDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClickNumber(View v) {
if (v.getId() == R.id.btnDot && (display.equals("") || display.contains("."))) {
return;
}
if ((v.getId() == R.id.btn0 ||
v.getId() == R.id.btn1 || v.getId() == R.id.btn2 ||
v.getId() == R.id.btn3 || v.getId() == R.id.btn4 ||
v.getId() == R.id.btn5 || v.getId() == R.id.btn6 ||
v.getId() == R.id.btn7 || v.getId() == R.id.btn8 ||
v.getId() == R.id.btn9) && (display.equals("0"))) {
clear();
updateScreen();
}
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
df.setMaximumIntegerDigits(3);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
public void onClickClear(View v) {
clear();
}
private void clear() {
display = "";
result = "";
textSubtractor.setText("0");
textResult.setText("0");
}
private void updateScreen() {
textSubtractor.setText(display);
}
For a simple solution, I would suggest checking the integer and decimal part of the input when new numeric button is pressed:
//Class constants
final static int INTEGER_SIZE = 3;
final static int DECIMAL_SIZE = 2;
public void buttonPressed(View v) {
if (v.getId() == R.id.btn_dot){ // Handle dot
if(!display.contains("."))
display+=".";
}else{ // Only number values reach this
if(display.equals("0")){ // Handle default zero
clear();
updateScreen();
}
if(display.contains(".")){ //If the number contains a dot, decimal length has to be checked
String[] split = display.split("\\.");
if(split.length==2 && split[1].length()==DECIMAL_SIZE)
return; // New number is not added
}else if(display.length()==INTEGER_SIZE) //Otherwise check the length of the integer (whole sting)
return; // New number is not added
// New number will be added
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
}
In the long run, you should consider giving user some feedback like disabling the buttons or showing maximum length of the number on UI.
I have 2 list, an array for imageviews and an array for the drawables :
List<Integer> imageViews = new ArrayList<Integer>();
List<Integer> images = new ArrayList<Integer>();
Here is where I add items in each list.
public void viewadd()
{
imageViews.add(R.id.star1);
imageViews.add(R.id.star2);
imageViews.add(R.id.star3);
imageViews.add(R.id.star4);
imageViews.add(R.id.star5);
imageViews.add(R.id.star6);
imageViews.add(R.id.star7);
imageViews.add(R.id.star8);
imageViews.add(R.id.star9);
imageViews.add(R.id.star10);
imageViews.add(R.id.star11);
imageViews.add(R.id.star12);
}
public void imageadd()
{
images.add(R.drawable.blue);
images.add(R.drawable.red);
images.add(R.drawable.green);
images.add(R.drawable.violet);
images.add(R.drawable.orange);
images.add(R.drawable.yellow);
images.add(R.drawable.blue);
images.add(R.drawable.red);
images.add(R.drawable.green);
images.add(R.drawable.violet);
images.add(R.drawable.orange);
images.add(R.drawable.yellow);
}
Now when I click on a specific star (or could be in the onCreate method), it should be randomized accordingly.
Random drawable in a random imageview :
View.OnClickListener tapHandler = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
imageadd();
viewadd();
Random rng = new Random();
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 12; i++)
{
while(true)
{
Integer next = rng.nextInt(imageViews.size()) ;
if (!generated.contains(next))
{
generated.add(next);
ImageView iv = (ImageView)findViewById(imageViews.get(next));
iv.setImageResource(images.get(next));
images.remove(next);
imageViews.remove(next);
break;
}
}
}
}
};
And so I want to know what was the last drawable used inside the for loop so I can set tag in it?
Just keep a reference to the last ImageView outside the loop.
// last image reference
Drawable lastImg = null;
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < 12; i++) {
while (true) {
Integer next = rng.nextInt(imageViews.size());
if (!generated.contains(next)) {
generated.add(next);
ImageView iv = (ImageView) findViewById(imageViews
.get(next));
iv.setImageResource(images.get(next));
// skip when i = 0
if (lastImg != null) {
iv.setTag(lastImg); // tag the last drawable
}
// store the current drawable
lastImg = getResources().getDrawable(images.get(next));
images.remove(next);
imageViews.remove(next);
break;
}
}
}
And, unless it serves some other purpose, you could also probably call imageadd() and viewadd() only once, and not on every onClick(). You would just have to skip calling images.remove() and imageViews.remove() from inside your loop then.
I'm attempting to work on a simple first Android app, and while eventually it will be a shake-to-activate app, right now it still works with the click of a button because I need to be able to test it on the emulator I have.
The end goal for the app is to, when the device is shaken, choose one random number out of three (each corresponds to a Character from a show) and read that number to fade in an image of that character. Directly after, it fades in a random quote from an array of quotes from that specific character.
Currently, I'd gotten the app working to the point where, when I clicked the button, the app chose a character, and a quote from the array for that character, and was able to fade the quote in. In trying to implement the image fading in, I've done something that makes the app crash when I try to run it.
I'm sure it'll be some stupid mistake, but it would be fantastic if it could be found.
The project has four class files: MainActivity.java, DoctorWho.java, Nine.java, Ten.java, and Eleven.java. Nine, Ten, and Eleven are all nearly identical, just using different quotes.
In trying to add the image fade-in, I added it to DoctorWho.java, here:
public class DoctorWho {
private Nine mNine = new Nine();
private Ten mTen = new Ten();
private Eleven mEleven = new Eleven();
private ImageView mImageView1;
private ImageView mImageView2;
private ImageView mImageView3;
int randomNumber = 0;
public String getDoctorQuote() {
String quote = "";
// Choose a Random number out of three values
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(3);
// Use that value to choose which of the Doctors to get a quote from
if (randomNumber == 0) {
// Quote from Nine
quote = mNine.getQuote();
}
else if (randomNumber == 1) {
// Quote from Ten
quote = mTen.getQuote();
}
else if (randomNumber == 2) {
// Quote from Eleven
quote = mEleven.getQuote();
}
else {
quote = "Error";
}
return quote;
}
public void animateDoctor() {
if (randomNumber == 0) {
animateNinthDoctor();
}
else if (randomNumber == 1) {
animateTenthDoctor();
}
else if (randomNumber == 2) {
animateEleventhDoctor();
}
}
private void animateNinthDoctor() {
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
mImageView1.setAnimation(fadeInAnimation);
}
private void animateTenthDoctor() {
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
mImageView2.setAnimation(fadeInAnimation);
}
private void animateEleventhDoctor() {
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
mImageView3.setAnimation(fadeInAnimation);
}
In my MainActivity.java file, I try to run the animation on-click here:
#Override
public void onClick(View arg0) {
String quote = mDoctorWho.getDoctorQuote();
mDoctorWho.animateDoctor();
// mQuoteLabel is the TextView where the quotes are displayed
mQuoteLabel.setText(quote);
animateQuoteIn();
}
The app still starts up fine, and no errors are shown before I run it on the emulator. When I click on the button that should run this sequence, the app crashes. There are no errors shown in the console, and I wasn't able to find a specific line in the LogCat view - I may be looking in the wrong place though. Let me know if updating the post with more code would be helpful in finding what is causing the crash.
Try changing you DoctorWho class as following:
Also have you initialized mImageView1,mImageView2,mImageView3 inside DoctorWho class???
public class DoctorWho {
private Nine mNine = new Nine();
private Ten mTen = new Ten();
private Eleven mEleven = new Eleven();
private ImageView mImageView1;
private ImageView mImageView2;
private ImageView mImageView3;
int randomNumber = 0;
public String getDoctorQuote() {
String quote = "";
// Choose a Random number out of three values
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(3);//<--- don't create new randonNumber
// Use that value to choose which of the Doctors to get a quote from
if (randomNumber == 0) {
// Quote from Nine
quote = mNine.getQuote();
}
else if (randomNumber == 1) {
// Quote from Ten
quote = mTen.getQuote();
}
else if (randomNumber == 2) {
// Quote from Eleven
quote = mEleven.getQuote();
}
else {
quote = "Error";
}
return quote;
}
public void animateDoctor() {
ImageView imageView=null;
if (randomNumber == 0) {
imageView=mImageView1;
}
else if (randomNumber == 1) {
imageView=mImageView2;
}
else if (randomNumber == 2) {
imageView=mImageView3;
}
AlphaAnimation fadeInAnimation = new AlphaAnimation(0, 1);
fadeInAnimation.setDuration(1500);
fadeInAnimation.setFillAfter(true);
imageView.setAnimation(fadeInAnimation);
}
}