Changing activity background by path - android

I try to change the background of my Activity ( onCreate ) randomly. It stucks in the the last step ... show it. Maybe someone has an idea for me.
I created an array within a xml file which contains 5+ drawable's - it looks like this ..
<array name="backgrounds">
<item>#drawable/bg1_320x480</item>
<item>#drawable/bg2_320x480</item>
<item>#drawable/bg3_320x480</item>
<item>#drawable/bg4_320x480</item>
<item>#drawable/bg5_320x480</item>
<item>#drawable/bg6_320x480</item>
</array>
Within my main activity, I get one random element out of the array ...
String[] mTempArray = getResources().getStringArray(R.array.backgrounds);
int iMin = 0;
int iMax = 5;
int randomIndex = iMin + (int) (Math.random() * iMax);
String resPath = mTempArray[randomIndex];
resPath return me (e.g.) res/drawable-hdpi/bg4_320x480.png. From this point on, I found a lot of solutions, but nothing brings me to succes.
What is the last point to set / change / overwrite the background?

A resource ID is just an integer--there's no need to deal with strings. You can use something like this
int[] imageIds = new int[] { R.drawable.bg1, R.drawable.bg2, ... };
, pick a random element, and set it as your background. Not sure if you can encode the array of resource IDs in xml.

Related

Creating resource reference ints programmatically

I am building a quiz app with questions in a string resource, as well as an answer. They are formatted by numbers like so:
<string name="ques1">What color is the sky?</string>
<string name="ques2">What sound does a cow make?</string>
The answers are also strings corresponding to the same number as the questions:
<string name="ans1">Blue</string>
<string name="ans2">Moo</string>
I have created a QA class for holding both a question and the answer, as well as the user's response from an EditText. At the "loading" of my app these classes are created and filled by reading from the strings resource.
I can programmatically enter these no problem, it is a lot of copy pasting but it will get the job done:
QA.setQuestion(getString(R.string.ques1));
QA.setAnswer(getString(R.string.ans1));
quizList.add(QA);
QA.setQuestion(getString(R.string.ques2));
QA.setAnswer(getString(R.string.ans2));
quizList.add(QA);
etc...
The problem is that I want to be able to add questions and answers to the xml at any time without having to add yet another repetition of the above method. What I want to do is essentially this:
String refBase = "R.string."
String ans = "ans";
String ques = "ques";
int numOfQues = 25; //only change when questions are added or removed
for (int i = 0; i < numOfQues; i++)
{
String referenceQ = refBase + ques + i;
String referenceA = refBase + ans + i;
QA.setQuestion(getString(referenceQ));
QA.setAnswer(getString(referenceA));
quizList.add(QA);
}
I cannot cast a string to an int like this obviously, but I am wondering if there is a way to implement a reference "builder", where I don't have to repeat many lines of code just to read another string with the same name but incremented number.
I understand that I can also just create an array.xml with one for questions and one for answers, making sure their position in each array corresponds. This would be easiest I think, but I guess I am wondering if it is possible to create references to string values through the code like my example?
You can use this method to get the question or answer String by its resource name:
String getQAString(boolean isQuestion, int index) {
String prefix = isQuestion? "ques" : "ans";
int resId = getResources().getIdentifier(prefix + index, "string", getPackageName());
return resId != 0? getString(resId) : "";
}
The loop to add questions and answers (assume they start from 1 and end at 25):
int numOfQues = 25;
for (int i = 1; i <= numOfQues; i++) {
String referenceQ = getQAString(true, i);
String referenceA = getQAString(false, i);
QA.setQuestion(referenceQ);
QA.setAnswer(referenceA);
quizList.add(QA);
}

Array of methods

I am trying to randomly call methods to make it use a different animation every time to display a textview. I trie using an array but not sure how to implement it. My array looks like this (obviously I know it shouldn't be strings but not sure what data type or if even possible this way).
String [] mAnimations = {"Hinge","RollIn", "Landing",
"BounceIn", "BounceInDown", "BounceInLeft", "BounceInRight",
"BounceInUp", "FadeIn", "FadeInUp", "FadeInDown", "FadeInLeft",
"FadeInRight","FlipInX", "RotateIn", "RotateInDownLeft", "RotateInDownRight",
"RotateInUpLeft", "RotateInUpRight", "SlideInLeft", "SlideInRight",
"SlideInUp", "SlideInDown", "ZoomIn", "ZoomInDown", "ZoomInLeft",
"ZoomInRight", "ZoomInUp"};
Putting any of the correct animations by themselves it works fine (Note BounceInLeft):
YoYo.with(Techniques.BounceInLeft)
.duration(1000)
.playOn(textView);
But what I am trying to do is randomly pick an animation from the array something like this:
Random rand = new Random();
int n = rand.nextInt(mAnimations.length) + 1;
YoYo.with(Techniques.(mAnimations[n]))
.duration(1000)
.playOn(textView);
Thanks for your help
Nicholas
Best Directly Assign method based on Random numbers.Because (mAnimations[n]) value consider as String.
String [] mAnimations = {"Hinge","RollIn", "Landing",
"BounceIn", "BounceInDown", "BounceInLeft", "BounceInRight",
"BounceInUp", "FadeIn", "FadeInUp", "FadeInDown", "FadeInLeft",
"FadeInRight","FlipInX", "RotateIn", "RotateInDownLeft", "RotateInDownRight",
"RotateInUpLeft", "RotateInUpRight", "SlideInLeft", "SlideInRight",
"SlideInUp", "SlideInDown", "ZoomIn", "ZoomInDown", "ZoomInLeft",
"ZoomInRight", "ZoomInUp"};
Random rand = new Random();
int n = rand.nextInt(mAnimations.length);
if(n==0)
{
YoYo.with(Techniques.Hinge).duration(1000).playOn(textView);
}
if(n==1)
{
YoYo.with(Techniques.RollIn).duration(1000).playOn(textView);
}

Is there a way to accept multiple view IDs as a parameter in xml?

So I have written a 'multi-sliding drawer' widget, which works like Slidingdrawer except it allows up to 4 'drawers'. However, I would really prefer to make this 'n-drawers', but the issue I have is with the parameters in xml. Currently, I am passing in the handles/contents via:
ns:handle1="#+id/slideHandleButton1"
ns:content1="#+id/contentLayout1"
ns:handle2="#+id/slideHandleButton2"
ns:content2="#+id/contentLayout2"
ns:handle3="#+id/slideHandleButton3"
ns:content3="#+id/contentLayout3"
but obviously there is some redundancy here. I originally thought I could just use 'getChild(i)' to cycle through the children and add them internally, but my understanding is that the getChild method returns children in visual order, not the order they were added in xml. So what I want to do now is something like:
ns:handles="#id/contentLayout1,#id/contentLayout2,#id/contentLayout13"
which would allow an arbitrary number of drawers. Is this possible? Or is there another good solution to this issue?
You can define your widget to have parameters (say, handles andcontents) that each takes a reference to an array. You can define the arrays using the standard notation:
res/values/arrays.xml
<array name="my_widget_layouts">
<item>#layout/contentLayout1</item>
<item>#layout/contentLayout2</item>
. . .
</array>
<array name="my_widget_buttons">
<item>#+id/slideHandleButton1</item>
<item>#+id/slideHandleButton2</item>
. . .
</array>
inside some layout:
<com.example.MyWidget
ns:contents="#array/my_widget_layouts"
ns:handles="#array/my_widget/buttons"
. . .
/>
Then in the Java code when you construct your widget:
MyWidget(Context context, AttributeSet attrs) {
Resources res = getResources();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyWidget);
// Get the ID of the array containing the content layout IDs for this widget
int contentsId = a.getResourceId(R.styleable.MyWidget_contents, 0);
if (contentsId > 0) {
// array of layouts specified
TypedArray ta = res.obtainTypedArray(contentsId);
int n = ca.length();
mContentLayoutIds = new int[n];
for (int i = 0; i < n; ++i) {
mContentLayoutIds[i] = ta.getResourceId(i, 0);
// error check: should never be 0
}
ta.recycle();
}
// similar code to retrieve the button IDs
if (mContentLayoutIds.length != mHandleIds.length) {
// content layout and button arrays not same length: throw an exception
}
. . .
a.recycle();
. . .
}

android dynamical binding

I want to work dynamically therefore I want to bind text views dynamically I think an example would explain me the best
assuming I want to bind 7 image views i can do it like this :
Country = (EditText)findViewById(R.id.CountryEditText);
City = (EditText)findViewById(R.id.CityEditText);
LivinigCreture = (EditText)findViewById(R.id.LivingCretureE);
Nature =(EditText)findViewById(R.id.NatureEditText);
Inanimate = (EditText)findViewById(R.id.InanimateEditText);
KnowenPersonality = (EditText)findViewById(R.id.KnowenPersonalityEditText);
Occupation = (EditText)findViewById(R.id.OccupationEditText);
but lets change 7 with NUMOFFILEDS as a final where i want to do the previous ?
myImages = new ImageView [7];
for (int i = 0; i<7;i++,????)
myImages[i] = (ImageView)findViewById(R.id.initialImageView01);
notice : in my R file the R.id.initialImageView01 - R.id.initialImageView07 are not generate in a cont gap between them therefore I don't know how to make this architecture possible .
and if there's a way can someone show me an example how to work dynmiclly (like using jsp on android combined way or something ?)
id its possiable to do so constant times is it possible to build an the same xml constant num of times like jsp does
thank u pep:)
You can store the IDs themselves in an array at the beginning of your Activity; that way you'll only need to write them once and you can index them afterwards.
Something like:
int[] initialImageViewIds = {
R.id.CountryEditText,
R.id.CityEditText,
R.id.LivingCretureE,
R.id.NatureEditText,
R.id.InanimateEditText,
R.id.KnowenPersonalityEditText,
R.id.OccupationEditText
};
Then you can access them with:
myImages = new ImageView [7];
for (int i = 0; i<7;i++) {
myImages[i] = (ImageView)findViewById(initialImageViewIds[i]);
}
If that's not enough and you really want to get the IDs dynamically, I suppose you can use reflection on the R.id class, possibly with something like R.id.getClass().getFields() and iterate on the fields to check if their names interest you. Check reference for the Class class, too.

Android: Set a random image using setImageResource

I need a help with setting a random image using setImageResource method.
In the drawable folder, I have a jpeg file named photo0.jpg, photo1.jpg...photo99.jpg.
And the following code works:
int p = R.drawable.photo1;
image.setImageResource(p);
The above will display photo1.jpg but I want to show a random image.
I tried the following but it doesn't work.
String a = "R.drawable.photo";
int n = (int) (Math.random()*100)
String b = Integer.toString(n);
String c = a+b;
int p = Integer.parseInt(c);//checkpoint
image.setImageResource(p);
It seems like the string "R.drawable.photoXX" isn't being changed to integer at the checkpoint.
Could someone please teach me a right code?
Thank you in advance.
Strings are pretty much evil when it comes to work like this due to the overhead costs. Since Android already provides you with integer id's I would recommend storing all of them to an int array and then using a random number for the index.
The code would look something like this:
int imageArr[] = new int[NUM_IMAGES];
imageArr[1] = R.drawable.photo;
//(load your array here with the resource ids)
int n = (int)Math.random()*NUM_IMAGES;
image.setImage(imageArr[n]);
Here we have a pretty straight forward implementation and bypass all the creation and destruction that occurs with the string concats.
maybe the error is here
int n = (int) (Math.random()*100)
put % not * Like this
int n = (int) (Math.random()%100)
to get all numbers under 100

Categories

Resources