Showing Images(or Media) on Button Click on Randomly changing Layouts - android

I want to show 5 xml layouts in random, and also i'l shuffle them on click of appropriate button each appeared xml file. Upto that the below code is working awesomely.----**I have put a delay of 0.75 seconds on each shuffle of the xml file.In this delay I have a sound to play.I have no really Idea How to achieve this.In the below code I used Switch-Case , But it is not working.My requirement is if I Click on the Button on xml file1 , I want to play Sound1, if the Button is from Xml file 5 , I want to play the corresponding Sound5 And so on....like that for 0.75 seconds and move to next XML file and the cycle repeats.*----
public class ReceivingActivity extends Activity{
Random random = new Random();
Handler handler = new Handler();
private int mPosition = 0;
private Handler mHandler = new Handler();
private List<Integer> mLayouts;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mLayouts = new ArrayList<Integer>();
mLayouts.add(R.layout.first);
mLayouts.add(R.layout.second);
mLayouts.add(R.layout.third);
mLayouts.add(R.layout.fourth);
mLayouts.add(R.layout.fifth);
Collections.shuffle(mLayouts);
setContentView(mLayouts.get(mPosition));
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
mPosition++;
}
private OnClickListener mListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "WTH is happening", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
if(mPosition >= mLayouts.size()){
int lastId = mLayouts.get(mLayouts.size() - 1);
Collections.shuffle(mLayouts);
while (lastId == mLayouts.get(0)) {
Collections.shuffle(mLayouts);
}
mPosition = 0;
}
setContentView(mLayouts.get(mPosition));
switch (mLayouts.get(mPosition)) {
case R.layout.first:
Toast.makeText(getApplicationContext(), "First", Toast.LENGTH_SHORT).show();
iv1.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.second:
Toast.makeText(getApplicationContext(), "second", Toast.LENGTH_SHORT).show();
//Some sound
iv2.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.third:
Toast.makeText(getApplicationContext(), "third", Toast.LENGTH_SHORT).show();
//Some media , Different for each Layout..
iv3.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.fourth:
Toast.makeText(getApplicationContext(), "fourth", Toast.LENGTH_SHORT).show();
iv4.setBackgroundResource(R.drawable.ic_launcher);
break;
case R.layout.fifth:
Toast.makeText(getApplicationContext(), "fifth", Toast.LENGTH_SHORT).show();
iv5.setBackgroundResource(R.drawable.ic_launcher);
break;
default:
break;
}
mPosition++;
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
}
}, 2050);
}
};
mPosition++;
mButton = (Button)findViewById(R.id.btnid);
mButton.setOnClickListener(mListener);
}
}, 750);
}
};
}
Any kind help is highly helpful.

You may use the android:tag to differentiate between the buttons.
<Button
...
android:tag="1"/>
And then in the code retrieve the tag
mButton = (Button)findViewById(R.id.btnid);
int id = Integer.parseInt(mButton.getTag());
switch(id) {
...
}

Related

Why can't function "if (counter >10)" work?

I'm trying to get an AlertDialog to appear if my counter is above 10.
I have tried using the TextView variable peopleCount in the if statement but it does not work too. I know using TextView will not work but I need to know if there is a workaround.
private TextView peopleCount;
private ImageView plusOne;
private ImageView minusOne;
private ImageView reset;
private int counter;
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.ivPlusOne :
plusCounter();
break;
case R.id.ivMinusOne :
minusCounter();
break;
case R.id.ivReset :
initCounter();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people);
peopleCount = (TextView)findViewById(R.id.tvPeopleCount);
plusOne = (ImageView)findViewById(R.id.ivPlusOne);
plusOne.setOnClickListener(clickListener);
minusOne = (ImageView)findViewById(R.id.ivMinusOne);
minusOne.setOnClickListener(clickListener);
reset = (ImageView)findViewById(R.id.ivReset);
reset.setOnClickListener(clickListener);
initCounter();
if( counter > 10) {
AlertDialog.Builder peopleAlert = new AlertDialog.Builder(PeopleActivity.this);
peopleAlert.setCancelable(false);
peopleAlert.setTitle("People Count High");
peopleAlert.setMessage("Please check and replenish inventory");
peopleAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogPeople, int which) {
dialogPeople.cancel();
}
});
peopleAlert.show();
}
private void initCounter(){
counter = 0;
peopleCount.setText(counter + "");
}
private void plusCounter(){
counter++;
peopleCount.setText(counter + "");
}
private void minusCounter(){
counter--;
peopleCount.setText(counter + "");
}
I expected the AlertDialog to appear when counter reached 11 but nothing happens.
OnCreate only runs once, You need to move the if statement to a function and call it from your plusCounter() and minusCounter() functions.

How to set if else condition on button being clicked or not in android?

I would like to know how to set an if else condition where the next button have to be disabled if none of the buttons are being clicked. Otherwise, they are able to proceed to next question?
private AdvancedQuestion nAdvancedQuestion = new AdvancedQuestion();
private TextView nScoresView;
private TextView nQuestionsView;
private TextView tvTime;
private Button nButtonChoices1;
private Button nButtonChoices2;
private Button nButtonChoices3;
private Button nButtonChoices4;
private String nAnswers;
private int nScores = 0;
private int nQuestionNumbers = 0;
Button btnNextz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_quiz);
updateQuestions();
nButtonChoices1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (nButtonChoices1.getText() == nAnswers) {
correctSound.start();
nScores = nScores + 1;
nButtonChoices1.setEnabled(false);
nButtonChoices2.setEnabled(false);
nButtonChoices3.setEnabled(false);
nButtonChoices4.setEnabled(false);
nButtonChoices1.getBackground().setColorFilter(Color.GREEN, PorterDuff.Mode.MULTIPLY);
Toast.makeText(advancedQuiz.this, "correct", Toast.LENGTH_SHORT).show();
} else {
wrongSound.start();
Toast.makeText(advancedQuiz.this, "wrong", Toast.LENGTH_SHORT).show();
nButtonChoices1.setEnabled(false);
nButtonChoices2.setEnabled(false);
nButtonChoices3.setEnabled(false);
nButtonChoices4.setEnabled(false);
}
}
});
btnNextz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextSound.start();
updateQuestions();
nButtonChoices1.setEnabled(true);
nButtonChoices2.setEnabled(true);
nButtonChoices3.setEnabled(true);
nButtonChoices4.setEnabled(true);
nButtonChoices1.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices2.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices3.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
nButtonChoices4.getBackground().setColorFilter(Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
private void updateQuestions() {
nQuestionsView.setText(nAdvancedQuestion.getQuestions(nQuestionNumbers));
nButtonChoices1.setText(nAdvancedQuestion.getChoices1(nQuestionNumbers));
nButtonChoices2.setText(nAdvancedQuestion.getChoices2(nQuestionNumbers));
nButtonChoices3.setText(nAdvancedQuestion.getChoices3(nQuestionNumbers));
nButtonChoices4.setText(nAdvancedQuestion.getChoices4(nQuestionNumbers));
nAnswers = nAdvancedQuestion.getCorrectAnswers(nQuestionNumbers);
nQuestionNumbers++;
}
private void updateScore(int points) {
nScoresView.setText("" + nScores);
}
Please note there is 4 possible answers. If none of them are selected, they cannot proceed to the next question until one button is press so they can go to the next question. The updateQuestions() is the part where i believe it will show next question.
This is a simple example on how to disable/enable a button based on an if condition -
int count = 0;
if (count == 0) {
NextButton.setEnabled(false);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.otherButtons:
count++;
NextButton.setEnabled(true);
Toast.makeText(this, "Button Disabled", Toast.LENGTH_LONG).show();
break;
case R.id.nextButton:
//Move the user to the next question
break;
}
}
Also check out this link
You will need to add a button element in the view of the activity you want it to appear on, then add an event listener to it either in the activity code or specify which function to call on click in the activities XML layout file.
See: https://developer.android.com/reference/android/widget/Button.html

android edittext addchangelistener

I have an application which has asks a user to input the amount of what he/she eats. The input field I used is an EditText. What I want to happen is when there's a change in the edittext, it should calculate (i.e., multiply the amount by its calories like 2 amount of bread is equal to 8 calories. So the answer should be 16 calories.)
But I can't get it to work. Please have a look on what I've tried:
UPDATED:
public class Bread_White extends Activity implements OnClickListener, OnItemSelectedListener {
Spinner sp;
Button calories, save, back, home;
String selected, strCalories;
TextView tv;
EditText etAmount;
int total;
RadioGroup rgMeal;
//RadioButton breakfast, ms, lunch, as, dinner, es;
String[] classes = {
"Cornbread",
"French Bread",
"French Toast",
"French Toast, low fat",
"Italian Bread",
"Wheat Bread",
"Wheat Bread, low calories",
"Wheat Bread, whole wheat"
};
//put how much calorie each food item has in this array
int[] intCalories = {188, 185, 126, 149, 81, 66, 46, 89};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.food_vegetable);
initControls();
}
private void initControls() {
// TODO Auto-generated method stub
// RadioGroup
rgMeal = (RadioGroup) findViewById (R.id.rgSelectMeal);
sp = (Spinner) findViewById (R.id.spFoodVegetable);
save = (Button) findViewById (R.id.btFoodVegetableSave);
calories = (Button) findViewById (R.id.btFoodVegetableCalories);
back = (Button) findViewById (R.id.tabs_back);
home = (Button) findViewById (R.id.tabs_home);
tv = (TextView) findViewById (R.id.txtMenuHeader);
etAmount = (EditText) findViewById (R.id.etAmount);
tv.setText(R.string.whitebread);
ArrayAdapter<String> array =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, classes);
sp.setAdapter(array);
sp.setOnItemSelectedListener(this);
back.setOnClickListener(this);
home.setOnClickListener(this);
save.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch( v.getId() ){
case R.id.btFoodVegetableSave:
String mealname = selected;
String serving = calories.getText().toString();
int i = Integer.parseInt(serving.replaceAll("[\\D]", ""));
//int amount = Integer.valueOf(etAmount.getText().toString());
//int answer = amount * i;
String strAnswer = String.valueOf(i);
//calories.setText(strAnswer);
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sdf.format(new Date());
if ( ( mealname.isEmpty() || strAnswer.isEmpty() ) ){
// call for custom toast
viewErrorToast();
}
else {
boolean didItWork = true;
try{
int checkedRadioButton = rgMeal.getCheckedRadioButtonId();
switch( checkedRadioButton ){
case R.id.rbBreakfast:
BreakFastLog bfLog = new BreakFastLog(Bread_White.this);
bfLog.open();
bfLog.createEntry(mealname, strAnswer, strDate);
bfLog.close();
break;
case R.id.rbMorningSnack:
MorningSnackLog msLog = new MorningSnackLog(Bread_White.this);
msLog.open();
msLog.createEntry(mealname, strAnswer, strDate);
msLog.close();
break;
case R.id.rbLunch:
LunchLog lunchLog = new LunchLog(Bread_White.this);
lunchLog.open();
lunchLog.createEntry(mealname, strAnswer, strDate);
lunchLog.close();
break;
case R.id.rbAfternoonSnack:
AfternoonSnackLog asLog = new AfternoonSnackLog(Bread_White.this);
asLog.open();
asLog.createEntry(mealname, strAnswer, strDate);
asLog.close();
break;
case R.id.rbDinner:
DinnerLog dinnerLog = new DinnerLog(Bread_White.this);
dinnerLog.open();
dinnerLog.createEntry(mealname, strAnswer, strDate);
dinnerLog.close();
break;
case R.id.rbEveningSnack:
EveningSnackLog esLog = new EveningSnackLog(Bread_White.this);
esLog.open();
esLog.createEntry(mealname, strAnswer, strDate);
esLog.close();
break;
}
}
catch(Exception e){
didItWork = false;
viewErrorToast();
}finally{
if (didItWork){
viewBMRSavedToast();
}
}
} // end of if else statement
break;
case R.id.tabs_back:
finish();
break;
case R.id.tabs_home:
Intent home = new Intent(this, IHealthFirstActivity.class);
home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home);
break;
}
}
private void viewBMRSavedToast() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();
}
private void viewErrorToast() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
selected = parent.getItemAtPosition(position).toString();
int amount = Integer.valueOf(etAmount.getText().toString());
total = amount * intCalories[position];
calories.setText(strCalories);
TextWatcher watcher = new TextWatcher(){
public void afterTextChanged(Editable s) {
//your business logic after text is changed
strCalories = total + " calories";
calories.setText(strCalories);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
//your business logic before text is changed
}
public void onTextChanged(CharSequence s, int start, int before, int count){
//your business logic while text has changed
}
};
etAmount.addTextChangedListener(watcher);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Please help fix this. Thanks.
Declare selectedPos as class level variable
int selectedPos = 0;
public void afterTextChanged(Editable s) {
//your business logic after text is changed
int cal = intCalories[selectedPos];
total = (Integer.parseInt(s.toString)) * cal;
calories.setText(total + " calories");
}
set your spinner selected position in defined variable.
Happy coding :)
Where is the calories view defined ? Also you might want to make that final. Could you rephrase the question. im not able to find that question :)

How to change background image of buttons after 4seconds in android? Not working

I have two buttons in my sample Android app. I want to select a button randomly and change its background image(to yellow) and display it for 4-seconds. After the 4-seconds now again I want to change the background image(to blue) and display it for 4-seconds. Now to repeat the process of buttons random selections and do the same with the radomly selected button as I stated above.
I have developed some code, when I test the code for indvidual button it works fine but when I run for both the buttons its not working accordingly.
Please help me, I would be very thankfull to you. You can check my code as wl....
int mainCount =0;// mainCount- could be a random number
int count_1 =0;
int count_2 =0;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mlayout);
mainHandler = new Handler();
mHandler1 = new Handler();
mHandler2 = new Handler();
.
.
.
mainRunnable.run();
}
Runnable mainRunnable = new Runnable(){
public void run(){
mainHandler.postDelayed(new Runnable(){
public void run(){
switch(mainCount){
case 0:
runButton1.run();
mainCount++; // mainCount- could be a random number to select a button randomly
break;
case 1:
runButton2.run();
mainCount++;// mainCount- could be a random number to select a button randomly
break;
}
if(count==2)
mainCount =0;
mainHandler.postDelayed(this,4000);
}
}, 4000);
}
};
Runnable runButton1 =new Runnable(){
public void run(){
mHandler1.postDelayed(new Runnable(){
public void run(){
switch(count_1){
case 0:
button1.setBackgroundResource(R.drawable.buttonyellow);
count_1++;
break;
case 1:
button1.setBackgroundResource(R.drawable.buttonblue);
count_1++;
break;
}
if(count_1==2)
count_1 = 0;
mHandler1.postDelayed(this,4000);
}
}, 4000);
}
};
Runnable runButton2 =new Runnable(){
public void run(){
mHandler2.postDelayed(new Runnable(){
public void run(){
switch(count_2){
case 0:
button2.setBackgroundResource(R.drawable.buttonyellow);
count_2++;
break;
case 1:
button2.setBackgroundResource(R.drawable.buttonblue);
count_2++;
break;
}
if(count_2==2)
count_2 = 0;
mHandler2.postDelayed(this,4000);
}
}, 4000);
}
};
First off, you don't need multiple Handlers, one will be enough. Second, you're calling mainRunnable.run() in onCreate to run another inner runnable so this would be better suited to just being a method. Regardless, here's my take:
public class MyActivity extends Activity {
private Runnable mEndlessRunnable;
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.my_activity);
mEndlessRunnable = new UpdateRunnable(new Handler(), new Button[] {
(Button) findViewById(R.id.button_1),
(Button) findViewById(R.id.button_2)
});
mEndlessRunnable.run();
}
private static class UpdateRunnable extends Runnable {
private Random mRand = new Random();
private Handler mHandler;
private Button[] mButtons;
private Button mCurButton;
private int mState;
public UpdateRunnable(Handler handler, Button[] buttons) {
mHandler = handler;
mButtons = buttons;
}
public void run() {
// select a button if one is not selected
if (mCurButton == null) {
mCurButton = mButtons[mRand.nextInt(mButtons.length)];
}
// check internal state, `0` means first bg change, `1` means last
switch (mState) {
case 0:
mCurButton.setBackgroundResource(R.drawable.blue_bg);
mState = 1;
break;
case 1:
mCurButton.setBackgroundResource(R.drawable.yellow_bg);
// reset state and nullify so this continues endlessly
mState = 0;
mCurButton = null;
break;
}
mHandler.postDelayed(this, 4000);
}
}
}
I haven't tested the above, but I'd use the above as a reference. Enjoy

Using a button and then showing dynamic text

I am writing a program that when the user enter a number text appears according to that number. My problem is that the button line has public void ... after this I am trying to use if statements and return methods, but because of the public void, the return method can not return anything. I tried to close the public void, but I am getting errors. Please help.
The code is as follows. I have included the different codes that I have tried like toast, etc..
ente#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.go);
button.setOnClickListener(mAddListener);
// tv = (TextView) findViewById(R.id.textView1);
}
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v) {
}}
;
//Toast.makeText(Num.this, "This Display", Toast.LENGTH_SHORT).show();
//toast.show();
//finish ();
// long id = 0;
// try
{
PleaseEnter=(EditText)findViewById(R.id.PleaseEnter);
{
}
if (PleaseEnter.equals("1"))
// tv.setText("This is the display 1.");
return "This display";
// Context context = getApplicationContext();
// CharSequence text ="this display";
// int duration =Toast.LENGTH_LONG;
// Toast toast =Toast.makeText(context, text, duration);
// toast.show();
else if (PleaseEnter.equals("2"))
return;
//tv.setText("Dispaly 2");
You can define your own method at Activity level, such as:
private void onTextEdited(String content) {
// deal with the String
}
In the onClick method of your OnClickListener, you can call it such as:
public void onClick(View v) {
EditText myEditText = (EditText) findViewById(R.id.PleaseEnter);
onTextEdited(myEditText.getText().toString());
}

Categories

Resources