Imageview to show different image depending on Int [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have a random number generator and I need to display different image,
depending on different Int values.
For example when randomNumber is let's say 1, I need to show specific text and image
and when number is 10 another specific text and image etc..
Can I even do that with ImageView, I do not know where to start?
package com.example.drinktivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main2Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button back = (Button) findViewById(R.id.buttonback); // Here the R.id.button1 is the button from you design
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(Main2Activity.this, MainActivity.class);
startActivity(i);
}
});
ImageView image = (ImageView) findViewById(R.id.imageView1);
Bundle bundle = getIntent().getExtras();
int random = bundle.getInt("Value");
TextView text = (TextView) findViewById(R.id.textView1);
if (random==1) {
text.setText("");
}
if (random==2) {
text.setText("");
}
if (random==3) {
text.setText("");
}
if (random==4) {
text.setText("");
}
if (random==5) {
text.setText("");
}
if (random==6) {
text.setText("");
}
if (random==7) {
text.setText("");
}
if (random==8) {
text.setText("");
}
if (random==9) {
text.setText("");
}
if (random==10) {
text.setText("");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Create a drawable array
public static final int[] im_smiley_drawable_smile_old = {
R.drawable.im_smiley_happy, R.drawable.im_smiley_sad,
R.drawable.im_smiley_winking,
R.drawable.im_smiley_tongue_sticking_out,
R.drawable.im_smiley_surprised, R.drawable.im_smiley_kissing,
R.drawable.im_smiley_yelling, R.drawable.im_smiley_cool}
send ramdom numbers to this array you will get random images

int[] i = {R.drawable.drawable1, R.drawable.drawable2, R.drawable.drawable2, R.drawable.drawable4, R.drawable.drawable5,};
Random rand = new Random();
int n = rand.nextInt(5);
imageView.setBackground(getResources().getDrawable(i[n]));

consider your int value as int random
and your random no consists of numbers 1 to 5.
then you can do this.
if(random==1){
imageview.setImageBitmap(yourbitmap);
//here imageview is your imageview. and then bitmap you want when the number generated is 1.
}

This is definitely possible, but there are a lot of ways of doing this. I think the main approach that you'd want to go for is generating a random number, and choosing an image from your resources based on that number. You can retrieve resources like this:
context.getResources().getIdentifier(i.getIcon(), "drawable", context.getPackageName())

Related

how to prevent a user from clicking on a button after another button has been clicked?

I am new to android programming and am building a quiz app in which a question has 4 options and if the user clicks on one of the options the other options should be unclickable. I am currently able to only make a single button unclickable. Here is the java code.
package com.example.android.quiz;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//This method is called when option 1 of question 1 is selected
public void verifyQuestion1Option1(View view) {
Button QuestionOption1 = (Button) findViewById(R.id.question1_option1);
QuestionOption1.setBackgroundColor(getResources().getColor(R.color.solid_red));
question1Answer();
}
public void verifyQuestion1Option2(View view) {
Button Question1Option2 = (Button) findViewById(R.id.question1_option2);
Question1Option2.setBackgroundColor(getResources().getColor(R.color.solid_red));//solid red is not a predefined colour. It is declared in colors.xml
question1Answer();
}
public void verifyQuestion1Option3(View view) {
Button Question1Option3 = (Button) findViewById(R.id.question1_option3);
Question1Option3.setBackgroundColor(getResources().getColor(R.color.solid_green));
question1Answer();
}
public void verifyQuestion1Option4(View view) {
Button Question1Option4 = (Button) findViewById(R.id.question1_option4);
Question1Option4.setBackgroundColor(getResources().getColor(R.color.solid_red));//We call the getResources() method because R.colour.solid_red passed the id of the color not the actual colour value.
question1Answer();
}
public void question1Answer() {
TextView q1Answer = (TextView) findViewById(R.id.question1_answer);
String answer = "Rajinish Kumar is the current Chairman of SBI who took over after Arundhati Bhattacharya retired on 6 October.Shikha Sharma is the Managing Director and CEO of Axis Bank and Chanda Kochhar is the managing director and CEO of ICICI Bank";
q1Answer.setText(answer);
}
}
Either you can use a buttongroup which will have only 1 active button at any point of time or else, you need to disable other button programatically.
To disable the button you can use the following code:
Button button = (Button) findViewById(R.id.button);
button.setEnabled(false);
You can use .setEnabled(false); to disable a button. That button will grey out and does not respond to click events any more.
To disable all buttons, get the handle to each button and set them to disabled.
Button Question1Option1 = (Button) findViewById(R.id.question1_option1);
Button Question1Option2 = (Button) findViewById(R.id.question1_option2);
Button Question1Option3 = (Button) findViewById(R.id.question1_option3);
Button Question1Option4 = (Button) findViewById(R.id.question1_option4);
Question1Option1.setEnabled(false);
Question1Option2.setEnabled(false);
Question1Option3.setEnabled(false);
Question1Option4.setEnabled(false);
That way, all buttons of this question become disabled.
You can also come up with a solution where you save that the button is already pressed and ignore further click events. You could introduce some sort of variable bool question1answered = false; that is set to true as soon as the onClick event is fired.
public void verifyQuestion1Option4(View view) {
if (question1Answered == true) {return;}
question1Answered =true;
//Do the rest of your checks here
}
Two tips for for programming Java:
Java (in contrast to i.e C#) used lower letter variables as convention.
Button question1Option1 = (Button) findViewById(R.id.question1_option1); would be a better way.
If you have more questions, it would make sense to put them in some sort of array and reuse the same four buttons multiple times. That would save you much programming overhead and code rewrites if you have to change something. And it keeps the code cleaner.

Setting up a if else statement with button in fragment, FuzFragment

First I must say that I'm not good in English and "completely new" to Android Programming.
I want to create an app that can monitor server performance. I have use the navigation drawer as my app interface. Each have a few fragment running with different sets of activity. One of the fragment, I would like to create an activity that can calculate the server performance using some if else statement calculation with a button to submit the results. When I run my app, I have trouble with this fragment (FuzFragment) where my app stopped immediately with an error "Unfortunately, ServerMonitorApp has stopped".
Below, is the fragment class (FuzFragment) that I used to display the layout:
package com.example.servermonitorapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FuzFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.fragment_fuz,
container, false);
Button sumButton = (Button) mLinearLayout.findViewById(R.id.submitButton);
sumButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText cpu = (EditText) v.findViewById(R.id.textCPU);
EditText ram = (EditText) v.findViewById(R.id.textRAM);
TextView res = (TextView) v.findViewById(R.id.txtResult);
int cpuslow = Integer.parseInt(cpu.getText().toString());
int cpusmedium = Integer.parseInt(cpu.getText().toString());
int cpushigh = Integer.parseInt(cpu.getText().toString());
int ramlow = Integer.parseInt(ram.getText().toString());
int rammedium = Integer.parseInt(ram.getText().toString());
int ramhigh = Integer.parseInt(ram.getText().toString());
if (cpuslow > 0 && cpuslow <= 30 | ramlow > 0 && ramlow <= 23) {
res.setText("Safe");
} else if (cpusmedium > 30 && cpusmedium <= 60 | rammedium > 23 && rammedium <= 38) {
res.setText("Risk");
} else if (cpushigh > 60 | ramhigh > 38) {
res.setText("Very Risk");
} else {
res.setText("Invalid Number");
}
}
});
return mLinearLayout;
}
}
Is there any wrong with my code that can cause my app stopped responding? Need help so much on this since I'm still in learning in Android programming.
Welcome to Android the dark side of development haha ;).
Ok let's go through a few basics.
The onCreate method is used to inflate or draw your layout. prior to having your layout drawn (if you do a findViewById) it won't exist.
In order for the onCreate method to draw the picture it needs the setContent method called that is created by default. This should be one of if not the first line of code you call. It ensures everything is available after that line for UI related interactions of an ACTIVITY. Emphasis on activity because the rules change when you get into fragments.
Now, the next issue is you have bloated code. Doing things like.
EditText myText = findViewById(R.id.myText);
int myValue = Integer.parseInt(myText.getText.toString());
etc.. can all be done in the same line and you are not using the reference to myText anywhere else so just do it like:
int myValue = Integer.parseInt(findViewById(R.id.myText).getText.toString());
Keep in mind I am doing Pseudo code. Please don't be that person that replies with " you have an error in your code " haha or I will not help.
Next up, it appears you never did the setContentView method in your onCreate, please put that back and set the content to your activity.xml code that matches the layout that you are inflating.
Next up, you are doing findViewById inside a button click. This is unnecessary repeat code. If you need to use the textView over and over then store a reference to it to avoid the repetitive lookup.
class MyClass{
EditText myTextBox;
protected void onCreate(stuff){
myTextBox = findViewById(R,id.myTextBox);
findViewById(R.id.myButton).setOnClickListener(new OnClickListener()){
#Override
protected void onClick(){
int myValue = Integer.parseInt(myTextBox.getText().toString());
}
});
}
Also for the record the onCreate should be very clean and to the point. I typically have a syncUI method that does my findViewById calls "prior to data binding days". I don't do that anymore, but new guys learning is fine.
Then in my syncUI I call wrapper methods to handle click listening instead of nesting in onCreate, but for now you are learning. But if you want a quick example..
onCreate(){
setContentView(myViewPointer from the R File);
syncUI();
}
private void syncUI(){
//SETUP TEXTVIEWS OR OTHER UIs that you need
//get btnSubmit reference from findViewByid
btnSubmit_onClick(); //called one time in onCreate to wrap the click listener into method that allows it to collapse and be easily found.
}
private btnSubmit_onClick(){
btnSubmit.setOnClickListener(new OnClickListener(){
#Override
protected void onClick(){
//handle Clicks
}
});
}
Thanks Sam for your reply..
I hv figure out one of my issue that cause my fragment stop responding when I run my app is might due to I mistaken declare my layout as LinearLayout in code above where else my actual layout in the myfragment.xml file is in Relativelayout (shown below).
LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.fragment_fuz,
container, false);
After I correct it my app can be open and the fragment related above also able to open. Only there's still problem when I try to run the code using few number sample and my app stop responding with same error "Unfortunately, ServerMonitorApp has stopped".

random number generator, android [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Can anyone help? I need to generate a random number, and then
public class MainActivity extends Activity implements OnClickListener {
TextView tv1;
Button bt1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.button1);
bt1.setOnClickListener(this);
tv1 =(TextView) findViewById(R.id.textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
Random r = new Random();
int i1=r.nextInt(80-65) + 65;
tv1 = (TextView) findViewById(R.id.textView1);
tv1.setText(i1);
break;};
}
}
And then it closes app after pushing button.
Change
tv1.setText(i1);
with
tv1.setText(String.valueOf(i1));
with tv1.setText(i1); you are looking for a String with id i1, inside string.xml. That id probably does not exists and will cause a crash for ResourcesNotFoundException
Edit: the tv1 = (TextView) findViewById(R.id.textView1); inside the onClick is useless since you are performing the same initialization inside the onCreate. Also you can move Random r = new Random(); inside the onCreate. Of course you have to keep r as class member

How to move a image View left and right in android development

I am very new to Android Development, and I am trying to develop a game. In this game, I will require a Imageview to move left and right when pressed by a button. My current IDE that I am using is "Android Studio". So I have done research but am not finding any answers. My current code is
package com.example.turtle;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
Button left, right ;
ImageView turtle ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
left = (Button) findViewById(R.id.bl);
right = (Button) findViewById(R.id.br);
turtle = (ImageView) findViewById(R.id.IVT);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
So yeah, As you can see I set up an OnClcikListener but I don't know what goes under it. I heard I can lessen a position, but how would I do that ? Like what is the code to lessen a position ? Thanks
At least for the newer Android studio this is how I would do it.
In your xml text code,(in your design/layout page go on the bottom and click text)
<Button
android:onClick="LeftBonClick"
(plus any additional xml code you have for this button.)
/>
And then on you java code...
public void LeftBonClick(View view) {
turtle.setX(turtle.getX() - 2); //<<code depending on your preference and what layout your turtle is in.
//add any code you want to happen here, when the left button is clicked
}
You can set the new parameteres for your ImageView with the following code inside onClick() method:
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(50,50, 0,0);
// OR
params.topMargin= 50;
turtle.setLayoutParams(params);
Hope that will help you.

How can I change Views in Layout by clicking a button in Android?

I'm taking Questions and Answers in String[].The TextView has questions and RadioButton has corresponding answers. If Start Button is clicked, first set of question and answers is displayed in Linear Layout1. If Next Button is clicked LinearLayout1 is replaced by next set of question with answers and again if Next Buttonis clicked next set of question has to be replaced and vice versa. Help me in writing code for Next Button
Note: Only LinearLayout 1 should be changed when clicking Next Button
code:
TextView tv;
RadioButton rb1, rb2;
Button bStart, bNext;
String question[] = { "Key Lime Pie is upcoming version",
"Android is Middleware", "Which is latest Android version?" };
String answerA[] = { "True", "False" };
String answerB[] = { "True", "False" };
String answerC[] = { "Android 4.2", "Android 5" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ques);
tv = (TextView) findViewById(R.id.textView111);
rb1 = (RadioButton) findViewById(R.id.radioButton1);
rb2 = (RadioButton) findViewById(R.id.radioButton2);
bStart = (Button) findViewById(R.id.startExam);
bNext = (Button) findViewById(R.id.bNext);
bStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText(question[0]);
rb1.setText(answerA[0]);
rb2.setText(answerA[1]);
}
});
bNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText(question[1]);
rb1.setText(answerB[0]);
rb2.setText(answerB[1]);
}
});
}
This is a logic problem.
Merge all the answers into a multidimensional array.
Keep track of the current question.
Use the tracking variable to get the question title in question.
Use the tracking variable to get the answers in the multidimensional array of answers. This is the first dimension of the array.
You read the answers in that dimension and display them in rb1 and rb2.
By using what you have there you will have problems extending that code. After all, are you really going to create a new variable for each different set of answers? It does not make any sense. A multidimensional array works.
However... although you can improve your arrays structure and use an int to keep track of the current displayed question (and thus increment it to get the next question after pressing the bNext), I suggest you try to create more meaningful objects, like a Question class, with relevant members (title, optionA, optionB, whatever...), especially because it looks like you're using this code to learn how to program a quiz-styled application.
Then you can create various questions and iterate through then.
But is that the issue there? No. The problem is keeping track of questions and answers. Use a multidimensional array with a tracking variable.
// edited: OK, I'm going to suggest something very quick for you:
static String[] questions = new String[] { "Question 1", "Question 2", "Question 3" };
static String[][] answers = new String[][] {
{"Answer 1.a", "Answer 1.b"},
{"Answer 2.a", "Answer 2.b"},
{"Answer 3.a", "Answer 3.b"},
};
int pos = -1;
void showNextAnswer() {
pos++;
tv.setText(questions[pos]);
rb1.setText(answers[pos][0]);
rb2.setText(answers[pos][1]);
}
bStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showNextAnswer();
}
});
bNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showNextAnswer();
}
});
As you can, both buttons do the same thing, so it's probably better to only use a next button.
Create a single array for answers. And declare tracking variables for questions and answers as:
String answer[] = {"True", "False" , "True", "False",
"Android 4.2", "Android 5" };
int current = 0; // this is your new variable
int ans = 1; // this is initialized to 1, because
// I assumed your first question and answer
// is displayed with the press of start button
Change your next button listener to this
public void onClick(View v) {
current ++;
if(current < question.length){
tv.setText(question[current]);
rb1.setText(answer[ans+=1]);
rb2.setText(answer[ans+=1]);
}
}

Categories

Resources