How do I display a Random number generated in a TextView? - java

I am generating random flashes of a button and I want to know what exact number is being chosen each time so I can eventually add them to an ArrayList for a project I am undergoing.
TextView randomTextView;
Random r = new Random();
private void sequenceFunction() {
//Change Alpha from Fully Visible to Invisible
final Animation animation = new AlphaAnimation(1, 0);
//Duration - A Second
animation.setDuration(1000);
//Animation Rate
animation.setInterpolator(new LinearInterpolator());
animation.setStartOffset(250);
animation.setDuration(250);
//Repeat Animation
animation.setRepeatCount(r.nextInt(10));
// Reverse animation at the end so the button will fade back in
animation.setRepeatMode(Animation.REVERSE);
//Button 1 Flashes
final Button btn = (Button) findViewById(R.id.button);
btn.startAnimation(animation);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
view.clearAnimation();
}
});
}
I want to display the result of what ever random number has been generated via the randomTextView TextView. This part is critical so that I know that the random function is working as it is supposed to. I have already tried
randomTextView.setText(r.nextInt(10));
However it didn't like it. Any ideas on how to get the random number selected would be greatly appreciated ?

Hope this helps -
private void sequenceFunction() {
//Change Alpha from Fully Visible to Invisible
final Animation animation = new AlphaAnimation(1, 0);
//Duration - A Second
animation.setDuration(1000);
//Animation Rate
animation.setInterpolator(new LinearInterpolator());
animation.setStartOffset(250);
//Repeat Animation
int randomValue = r.nextInt();
// code to add value to array
animation.setRepeatCount(randomValue);
randomTextView.setText(String.valueOf(randomValue));
// Reverse animation at the end so the button will fade back in
animation.setRepeatMode(Animation.REVERSE);
//Button 1 Flashes
final Button btn = (Button) findViewById(R.id.button);
btn.startAnimation(animation);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
view.clearAnimation();
}
});
}

If you have look in the documentation of TextView, you can see that setText(int) actually expects a resource id: https://developer.android.com/reference/android/widget/TextView.html#setText(int)
So you have to turn your int to a CharSequence, you could simply do
randomTextView.setText("" + r.nextInt(10));
which converts your integer to a string.

TextView.setText can be used with either a resource ID (which is an integer) or with a CharSequence, for example a String.
There are many ways to do this, including
int random = r.nextInt(10);
randomTextView.setText(String.valueOf(random);
randomTextView.setText(Integer.toString(random);
randomTextView.setText(String.format("%d", random);
Do not use "" + r.nextInt(10). I know, it is short, it is handy, but it is simply inefficient and bad style.

Related

moving Image View from point to another

I would like to move an image view from one point to another when a particular button is clicked.
Here's my code:
int e = 0 ;
Button d = (Button)findViewById(R.id.button1);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TranslateAnimation move = new TranslateAnimation(e, e + 1, e, e + 1);
move.setDuration(1000);
move.setFillAfter(true);
image.startAnimation(move);
}
});
But when I clicked the button nothing happened!
How do I make it work ?
Your animation probably works but it will only move the view by one pixel, which is not that noticeable. Try changing the values of your translate animation.

Android Button Not moving onclick

I have an up button which I want to move up onClick but when I click on it it moves way to far and gets to the end of the screen and then shrinks down untill you cant see it. It moves up too much, but why? I only increase it by one unit?
final Button upbutton = (Button)findViewById(R.id.upbutton);
upbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams)
upbutton.getLayoutParams();
mParams.bottomMargin += 1;
upbutton.setLayoutParams(mParams);
}
});
}
Because you're not assigning mParams to your buttons params.
mParams = upbutton.getLayoutParams();
You seem to be increasing parameters for your RelativeLayout then assigning those to your button. So the button gets confused. Try looking for a set margin option or something on the actual button view.

How to set font size for text of dialog buttons

I have an android app that uses some custom dialogs which are inflated from XML layouts. The contents of the dialog's view come from the XML layout, but the actual positive and negative buttons are added by calling the builder's setPositiveButton and setNegativeButton methods, so I have no control over (or at least don't know how to control) the styling of the buttons themselves.
See the onCreateDialog method below from my LoginConfirmationDialog.java file which extends DialogFragment. It basically pops a very simple dialog up that asks for confirmation of who is logging in (i.e. "Are you Joe Schmoe?", with Yes and No buttons).
The XML layout in this case has just a single TextView, and to make this easy (because the users will be construction workers with big knobby dirty fingers who need large text and large buttons), I made the font for the TextView pretty big. The two buttons though have much smaller font for their text, and since they aren't part of my layout and are added with the setPositiveButton and setNegativeButton methods, how do I control the font size?
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = this.getArguments();
String empName = args.getString("empName");
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_login_confirmation, null);
TextView message = (TextView)view.findViewById(R.id.txtLoginConfirmationMessage);
message.setText("Are you " + empName + "?");
builder.setView(view);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onEmpConfirmPositiveClick(LoginConfirmationDialog.this);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onEmpConfirmNegativeClick(LoginConfirmationDialog.this);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
Instead of returning builder.create(), try this.-
final AlertDialog alert = builder.create();
alert.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button btnPositive = alert.getButton(Dialog.BUTTON_POSITIVE);
btnPositive.setTextSize(TEXT_SIZE);
Button btnNegative = alert.getButton(Dialog.BUTTON_NEGATIVE);
btnNegative.setTextSize(TEXT_SIZE);
}
});
return alert;
Took me a while, to integrate Asok's answer, since I used anonymous inner classes for buttons, so I needed to get a handle on the button references. This works. Make sure it goes after the messageDialog.show() line:
messageDialog.show();
messageDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(TypedValue.COMPLEX_UNIT_SP, 25.0f);
messageDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextSize(TypedValue.COMPLEX_UNIT_SP, 25.0f);
Note: It's recommended to use sp as a unit for text size. Unlike px, it is device density independent.
You can try this:
AlertDialog.Builder builder = new AlertDialog.Builder(CompQuestionsActivity.this);
builder.setMessage("Message");
builder.setPositiveButton("Yes", dialogClickListener);
builder.setNegativeButton("No", dialogClickListener);
AlertDialog alertDialog = builder.create();
alertDialog.show();
//For positive button:
Button button1 = alertDialog.findViewById(android.R.id.button1);
button1.setTextSize(25);
//For negative button:
Button button2 = alertDialog.findViewById(android.R.id.button2);
button2.setTextSize(25);
Since you are already using an xml file for the dialog why not just include the two buttons in the layout and set the onClick handlers in the dialog creation, something like this should work. I am using something similar.
Here is a quick example:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_login_confirmation, null);
TextView message = (TextView)view.findViewById(R.id.txtLoginConfirmationMessage);
message.setText("Are you " + empName + "?");
Button positiveBtn = (Button) view.findViewById(R.id.dialogButtonPositive);
// Set size of button in relation to screen size
positiveBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) 25);
positiveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mListener.onEmpConfirmPositiveClick(LoginConfirmationDialog.this);
}
});
Button negativeBtn = (Button) view.findViewById(R.id.dialogButtonNeg);
// Set size of button in relation to screen size
negativeBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) 25);
negativeBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mListener.onEmpConfirmNegativeClick(LoginConfirmationDialog.this);
}
});
builder.setView(view);
return builder.create();
I am also quite fond of using the following for setting text sizes, this allows for various screen sizes to get a different size of text (You can play with the float value to suit your needs):
.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) 25);
You should check out the following answer:
In Dialog.java (Android src) a ContextThemeWrapper is used. So you could copy the idea and do something
You just have to change the following line of code:
<item name="android:textSize">10sp</item> to your desired size.
And don't forget to check the comments of the answer also.
Best of luck.
I have tried many devices using setOnShowListener . But it did not work for all devices. In the end I come to a decision that the most easiest way is to using a Theme for your alertDialog.
Add this to the style file.
<style name="MyAlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:textSize">10sp</item>
</style>
Now Use this in your AlertDialog
val dialog = AlertDialog.Builder(requireActivity(),R.style.MyAlertDialogTheme)
Thats all.
My approach is to obtain the buttons in onResume() and configure them there
public class LoginConfirmationDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// your code here remains unchanged
}
#Override
public void onResume() {
super.onResume();
Button positiveButton = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
Button negativeButton = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_NEGATIVE);
negativeButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
}
}

Can't find the way to move an image (or others clickable objects)

public class FirstTest extends Activity {
public FirstTest() {
// TODO Auto-generated constructor stub
}
RelativeLayout currentLayout;
static int[] Deck = {
R.drawable.img1,
R.drawable.img2,
R.drawable.img3,
R.drawable.img4
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentLayout = new RelativeLayout(this);
for (int i = 0; i < Deck.length; i++) {
ImageButton img = new ImageButton(this);
img.setPadding(0, 0, 0, 0);
img.setImageResource(Deck[i]);
img.setAdjustViewBounds(true);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// BUT HOW MOVE THIS BUTTON????
}
});
currentLayout.addView(img);
}
setContentView(currentLayout);
}
}
Maybe it's trivial for others, but I just found width and height property modifiers. After trying a lot of examples I gave up.
How can I move something? Why can't I find x y properties?
In your comment you mention how the image 'flashes' when it arrives at it's destination and then you no doubt set the image translation to the new position.
After much testing I found the best way to move an image (or any view) is to perform the steps in the following order:
On Click Event:
1. Find the coordinates of where you want the image to move to
2. Translate (set the position of) the image to where you want it to finish
3. Start an animation which starts from where the image was originally and ends back at it's current position (0,0).
Because the image has been moved to the end location and then instantly starts an animation you don't get any flashing at the beginning of the animation, then when the animation finishes it will end exactly where the image is already set to so you don't get any flashing at the end either.
It is a little strange but I believe it's just because of how Android triggers the Start/End Animation events.
I hope that makes sense.

Dynamically adding Buttons in Android doesn't work after the first Button is added

I have a button that I have created in code, which has a listener for Click events. Every time that the button is clicked, it should generate another button and add it below the original button. However, no matter how many times I click the first button, it will only add a dynamic button once, and not add any more.
Here is my coding:
public class DynaminControlActivity extends Activity {
private RelativeLayout container;
private int mainIdCnt = 0;
private int mainId = 100;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createMainButton();
}
public void createMainButton() {
container = (RelativeLayout) findViewById(R.id.workLayout);
Button b = new Button(this);
b.setId(mainIdCnt + mainId);
CharSequence text = "Main +";
b.setText(text);
container.addView(b);
if (mainId > 0) {
mainId++;
}
b.setOnClickListener((new View.OnClickListener() {
public void onClick(View v) {
createDynamicButton();
}
}));
}
public void createDynamicButton() {
container = (RelativeLayout) findViewById(R.id.workLayout);
Button b = new Button(this);
CharSequence text = "Main +";
b.setText(text);
RelativeLayout.LayoutParams relLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relLayout.addRule(RelativeLayout.BELOW, mainIdCnt + mainId);
container.addView(b, relLayout);
if (mainId > 0) {
mainId++;
}
}
A few things...
If your main layout is a LinearLayout, you shouldn't need to add a rule to indicate that the button should appear underneath the existing button - it will automatically be added to the very bottom (vertical alignment) or very right (horizontal alignment) of the layout.
All your buttons have the same text. Are you certain that you're clicking the first button each time? I note that only your first button has a listener on it, so if you're accidentally clicking one of the other buttons then nothing will happen.
If you're intending to add multiple buttons, it will quickly expand to be larger than the screen size, so you should make sure that your main layout is within a ScrollView so that you can see all the buttons you add
The call to setId() might be stuffing around with the internal workings of Android. Rather than setting an ID, you should let Android generate the ID automatically, and just retrieve that value if you need to reference it.

Categories