I want a test for 3-4 years old childs. I want if they click different apple , true count must plus one. And if they click one of same aplles false count must plus one. And click any apple the question and apples are must change.
My friend helped me and we did much of them. On clicks question and answers changing. But when click any apple wrong count plus one no matter it's true or false answer.
Can u pls help me?
We think we only have problems on if commands. He tried on it so much but couldn't solve the problem.
class file:
package tr.com.blogspot.etkinlikhavuzu.benimilkogretmenim;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by erisk on 31.01.2017.
*/
public class AA extends Activity implements View.OnClickListener{
TextView soru,dogrusayi,yanlissayi;
ImageView secenek1,secenek2,secenek3;
ArrayList<Soru> sorular;
Random random;
int dogruSayisi,yanlisSayisi,sayac,dogruCevap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.aa);
init();
sorulariYukle();
}
public void init(){
secenek1 = (ImageView) findViewById(R.id.secenek1);
secenek1.setOnClickListener(this);
secenek2 = (ImageView) findViewById(R.id.secenek2);
secenek2.setOnClickListener(this);
secenek3 = (ImageView) findViewById(R.id.secenek3);
secenek3.setOnClickListener(this);
soru = (TextView) findViewById(R.id.soru);
dogrusayi = (TextView) findViewById(R.id.dogrusayi);
yanlissayi = (TextView) findViewById(R.id.yanlissayi);
sorular = new ArrayList<Soru>();
random = new Random();
}
public void sorulariYukle(){
sorular.add(new Soru("Hangi Elma Yeşildir?",R.drawable.yesilelma,R.drawable.kirmizielma,R.drawable.kirmizielma,R.drawable.yesilelma));
sorular.add(new Soru("Hangi Elma Kırmızıdır?",R.drawable.kirmizielma,R.drawable.yesilelma,R.drawable.yesilelma,R.drawable.kirmizielma));
sorular.add(new Soru("Hangi Elma Yeşildir?",R.drawable.kirmizielma,R.drawable.yesilelma,R.drawable.kirmizielma,R.drawable.yesilelma));
sorular.add(new Soru("Hangi Elma Kırmızıdır?",R.drawable.yesilelma,R.drawable.yesilelma,R.drawable.kirmizielma,R.drawable.kirmizielma));
sorular.add(new Soru("Hangi Elma Yeşildir?",R.drawable.kirmizielma,R.drawable.kirmizielma,R.drawable.yesilelma,R.drawable.yesilelma));
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.secenek1:
if(secenek1.getDrawable() == getResources().getDrawable(dogruCevap)){
dogruSayisi++;
dogrusayi.setText(String.valueOf(dogruSayisi));
}else{
yanlisSayisi++;
yanlissayi.setText(String.valueOf(yanlisSayisi));
}
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
break;
case R.id.secenek2:
if(secenek2.getDrawable() == getResources().getDrawable(dogruCevap)){
dogruSayisi++;
dogrusayi.setText(String.valueOf(dogruSayisi));
}else{
yanlisSayisi++;
yanlissayi.setText(String.valueOf(yanlisSayisi));
}
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
break;
case R.id.secenek3:
if(secenek3.getDrawable() == getResources().getDrawable(dogruCevap)){
dogruSayisi++;
dogrusayi.setText(String.valueOf(dogruSayisi));
}else{
yanlisSayisi++;
yanlissayi.setText(String.valueOf(yanlisSayisi));
}
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
break;
}
}
}
xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="tr.com.blogspot.etkinlikhavuzu.benimilkogretmenim.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp">
<Button
android:id="#+id/dogru"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/dogru" />
<Button
android:id="#+id/yanlis"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/dogru"
android:layout_marginTop="10dp"
android:background="#drawable/yanlis" />
<TextView
android:id="#+id/dogrusayi"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_above="#+id/yanlis"
android:layout_toEndOf="#+id/dogru"
android:layout_toRightOf="#+id/dogru"
android:gravity="center"
android:text="#string/dogrusayi"
android:textColor="#006600"
android:textSize="30sp" />
<TextView
android:id="#+id/yanlissayi"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignBottom="#+id/yanlis"
android:layout_toEndOf="#+id/yanlis"
android:layout_toRightOf="#+id/yanlis"
android:gravity="center"
android:text="#string/yanlissayi"
android:textColor="#990000"
android:textSize="30sp" />
<ImageView
android:id="#+id/secenek1"
android:layout_width="170dp"
android:layout_height="170dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:id="#+id/secenek2"
android:layout_width="170dp"
android:layout_height="170dp"
android:layout_alignBottom="#+id/secenek1"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/secenek3"
android:layout_width="170dp"
android:layout_height="170dp"
android:layout_alignBottom="#+id/secenek2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/soru"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/secenek2"
android:layout_marginBottom="18dp"
android:layout_toEndOf="#+id/dogrusayi"
android:layout_toRightOf="#+id/dogrusayi"
android:gravity="center"
android:text="Hangi Elma Yeşildir?"
android:textColor="#006600"
android:textSize="40sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/siradaki"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#000000" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="1" />
</RelativeLayout>
</RelativeLayout>
And Soru.class file
package tr.com.blogspot.etkinlikhavuzu.benimilkogretmenim;
/**
* Created by erisk on 31.01.2017.
*/
public class Soru {
String soru;
int secenek1,secenek2,secenek3,dogruCevap;
public Soru(String soru, int secenek1, int secenek2, int secenek3, int dogruCevap) {
this.soru = soru;
this.secenek1 = secenek1;
this.secenek2 = secenek2;
this.secenek3 = secenek3;
this.dogruCevap = dogruCevap;
}
public String getSoru() {
return soru;
}
public void setSoru(String soru) {
this.soru = soru;
}
public int getSecenek1() {
return secenek1;
}
public void setSecenek1(int secenek1) {
this.secenek1 = secenek1;
}
public int getSecenek2() {
return secenek2;
}
public void setSecenek2(int secenek2) {
this.secenek2 = secenek2;
}
public int getSecenek3() {
return secenek3;
}
public void setSecenek3(int secenek3) {
this.secenek3 = secenek3;
}
public int getDogruCevap() {
return dogruCevap;
}
public void setDogruCevap(int dogruCevap) {
this.dogruCevap = dogruCevap;
}
}
Thank you so much
You are comparing drawables. which never matches.
Change your if(CONDITION) to following:
if(secenek1.getDrawable().getConstantState().equals(getResources().getDrawable(dogruCevap).getConstantState())).
same way for other two cases.
Related
I've created a spinner that takes some user-generated strings (in my case classes - the school type) and displays them in a typical spinner way. My problem occurs when trying to select an item from the spinner. I can tap on the spinner and select the class, but the spinner never shows that I have the class selected. Before adding user-generated strings, I had a string-array xml file that worked perfectly.
I've tried adding notifyDataSetChanged() at the end of the onCreate() method, created a spinner layout with a transparent background and black text, and setting an setOnItemSelectedListener(). None of these worked, so I reverted code back to original state.
Screenshot of problem:
addAssignment.java
package com.nbdeg.unityplanner;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nbdeg.unityplanner.data.Assignments;
import com.nbdeg.unityplanner.data.Classes;
import java.util.ArrayList;
public class addAssignment extends AppCompatActivity {
EditText mAssignmentName;
EditText mDueDate;
EditText mExtraInfo;
Spinner mDueClass;
SeekBar mPercentComplete;
int percentComplete = 0;
FirebaseAnalytics mFirebaseAnalytics;
DatabaseReference assignmentDb;
DatabaseReference classDb;
FirebaseUser user;
long assignmentCounter;
ArrayList<String> classList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_assignment);
// Sets title to "Create an assignment"
try {getSupportActionBar().setTitle("Create An Assignment");}
catch (NullPointerException e) {
e.printStackTrace();
}
// Getting number of assignments (serves as assignment ID in database)
Bundle extras = getIntent().getExtras();
assignmentCounter = extras.getLong("counter");
// Finds firebase database
user = FirebaseAuth.getInstance().getCurrentUser();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
assignmentDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("assignments");
classDb = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("classes");
// Gets all classes
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i("Info", "Class loaded: " + mClass.getClassName());
classList.add(mClass.getClassName());
}
Log.i("Info", "Classes loaded: " + classList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DB", "Error: " + databaseError.getMessage());
}
});
// Find view by ID calls
mAssignmentName = (EditText) findViewById(R.id.assignment_name);
mDueDate = (EditText) findViewById(R.id.due_date_edittext);
mExtraInfo = (EditText) findViewById(R.id.extra_homework_info);
mDueClass = (Spinner) findViewById(R.id.class_spinner);
mPercentComplete = (SeekBar) findViewById(R.id.percentComplete);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
// Sets DueDate EditText to open a datepicker when clicked
new EditTextDatePicker(this, R.id.due_date_edittext);
mPercentComplete.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
percentComplete = progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
// Adds a SAVE button to the Action Bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
// Gets and saves information when SAVE is clicked
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Getting information from views
String dueDate = mDueDate.getText().toString();
String assignmentName = mAssignmentName.getText().toString();
String extraInfo = mExtraInfo.getText().toString();
String dueClass = mDueClass.getItemAtPosition(mDueClass.getSelectedItemPosition()).toString();
mFirebaseAnalytics.logEvent("Assignment Created", null);
Log.i("DB", "Creating assignment named " + assignmentName);
assignmentDb.child(Long.toString(assignmentCounter)).setValue
(new Assignments(assignmentName, dueClass, dueDate, extraInfo, percentComplete));
/*
// Test to make sure info is being collected correctly.
Log.i("Class", dueClass);
Log.i("Due", dueDate);
Log.i("Name", homeworkName);
Log.i("Extra", extraInfo);
*/
// Bring user back to MainActivity
startActivity(new Intent(addAssignment.this, MainActivity.class));
return super.onOptionsItemSelected(item);
}
}
activity_add_assignment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_add_homework"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.nbdeg.unityplanner.addAssignment">
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="textCapSentences"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/assignment_name"
android:hint="Assignment Name"
android:padding="5dp"
android:textSize="18sp"
android:background="#null" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/assignment_name"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="43dp"
android:orientation="horizontal"
android:layout_below="#id/assignment_name"
android:layout_alignParentStart="true"
android:id="#+id/linearLayout">
<Spinner
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/class_spinner"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
android:layout_weight="1"
android:background="#null"/>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#c0c0c0"/>
<EditText
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/due_date_edittext"
android:padding="5dp"
android:focusable="false"
android:hint="Due Date"
android:textSize="16sp"
android:background="#null" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/linearLayout"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_below="#+id/linearLayout"
android:layout_alignParentStart="true"
android:id="#+id/percentCompleteLayout"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Completion"
android:padding="5dp"
android:textColor="#color/black"
android:textSize="15sp"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/percentComplete"
android:layout_marginBottom="1dp"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#c0c0c0"
android:layout_below="#id/percentCompleteLayout"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/extra_homework_info"
android:hint="Extra Infomation"
android:textSize="16sp"
android:layout_below="#id/percentCompleteLayout"
android:layout_alignParentStart="true"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#null" />
</RelativeLayout>
spinner_layout.xml*
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:gravity="left"
android:padding="5dip"
android:textColor="#android:color/black"
android:background="#android:color/transparent"
/>
I'm wondering if there is a way to fix this and have the spinner display the default / user choice. If you need any more of the code, all of it can be found in the GitHub. Thanks in advance for all answers!
Solution: Try loading the classes prior to starting the activity, for example in the MainActivity. Then pass the values along through an intent.
Example:
MainActivty.java
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launch Add Homework Activity
Intent intent = new Intent(MainActivity.this, addAssignment.class);
intent.putExtra("classListNames", classListNames);
startActivity(intent);
...
classDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
classList.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Classes mClass = userSnapshot.getValue(Classes.class);
Log.i(TAG, "Class loaded: " + mClass.getClassName());
classList.add(mClass);
classListNames.add(mClass.getClassName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Error: " + databaseError.getMessage());
}
});
addAssignment.java
// Gets class list
Bundle extras = getIntent().getExtras();
classListNames = extras.getStringArrayList("classListNames");
...
mDueClass = (Spinner) findViewById(R.id.class_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, classListNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mDueClass.setAdapter(adapter);
Cause: After some debugging, I discovered the cause of the problem to be timing differences. The app would request the classes be sent, create the spinner, then load the classes. The difference in timing was milliseconds, but just enough to cause the problem.
I have 4 different buttons. I want to change the background of the buttons at a fixed time (say 1 sec i.e. one button changes its color for one sec then retains its previous color and then other button does the same and so on) in certain random pattern, and then the user will repeat this pattern. However I am unable to change the background of the buttons randomly. I know that a timer or handler will b used but I have no idea ho to use it. Can anyone post a example program that shows how to change the background of buttons randomly?
here is my xml file:
`
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<TextView
android:id="#+id/levelText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="50dp"
android:textColor="#FFFFFF"
android:text = "" />
<TextView
android:id="#+id/countDnText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="100dp"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:text=""
/>
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button5"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="79dp" />
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button6"
android:layout_alignTop="#+id/button5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button7"
android:layout_below="#+id/button5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button8"
android:layout_alignTop="#+id/button7"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
`
here is my Activity:`
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class EasyGameActivity extends AppCompatActivity
{
private int counter;
private TextView text;
private boolean flag = false;
private Button button = null;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy_game);
startGame();
}
public void startGame()
{
counter = 3;
int temp;
final Random rand = new Random();
Handler handler = new Handler();
while(true)
{
BinaryTree binaryTree = new BinaryTree(counter);
for(int i = 0; i<counter; ++i)
{
temp = rand.nextInt(3);
// yellow color button...
if(temp == 0)
{
button = (Button) findViewById(R.id.button5);
button.setBackgroundColor(Color.YELLOW);
}
else if(temp == 1)
{
button = (Button) findViewById(R.id.button6);
button.setBackgroundColor(Color.BLUE);
}
else if(temp == 2)
{
button = (Button) findViewById(R.id.button7);
button.setBackgroundColor(Color.RED);
}
else if(temp == 3)
{
button = (Button) findViewById(R.id.button8);
button.setBackgroundColor(Color.GREEN);
}
//button.setBackgroundColor(Color.BLACK);
}
break;
}
}
}`
You could try something like this:
Button[] changingButtons = new Button[4];
changingButtons[0] = (Button)findViewById(R.id.button1_id);
changingButtons[1] = (Button)findViewById(R.id.button2_id);
changingButtons[2] = (Button)findViewById(R.id.button3_id);
changingButtons[3] = (Button)findViewById(R.id.button4_id);
You can then access the corresponding button in the array and change the background colour using changingButtons[<desired index>].setBackgroundResource(<color resource>)
To retain the previous color, you can use ColorDrawable previousBackground = (ColorDrawable)changingButtons[<desired index>].getBackground();
Then, for the "set time" part, use a timer, and do the colour switching in the TimerTask.
If you wish to use a TimerTask would look something like this inside the method calling it:
timer = new Timer();
timer.schedule(new MyTask(buttonNumber), numMilliseconds);
And then MyTask would be an extension class of TimeTask
class MyTask extends TimerTask
{
private int buttonId;
public MyTask(int buttonId)
{
super();
this.buttonId = buttonId;
}
public void run()
{
//Do your button alterations here
}
}
Here's a sample I made using the above code on Ideone
Hopefully this points you in the right direction!
For more information, check out these: Changing the background color programmatically, Getting the background color, Java Timer documentation
You can use Collections.shuffle(colorList);
List<String> colorList=new ArrayList<>();
colorList.add("#108E44");
colorList.add("#000000ff");
colorList.add("#108E44");
for() {
giveMeButtons(i).setBackgorundColor(Color.parseColor(colorList.get(i)));
}
And you must make other method. It will return random View button.
I want to create a program in which when i press the Up Button the Ball image moves towards the top 1px
and when i press the Down Button the image moves to Bottom .
Now Tell me how i get this output.
I did a demo project of your requiremens, and this is how the code looks like:
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/ballImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/ic_launcher"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:gravity="center">
<Button
android:id="#+id/upBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Up" />
<Button
android:id="#+id/downBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Down" />
<Button
android:id="#+id/leftBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left" />
<Button
android:id="#+id/rightBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right" />
</LinearLayout>
</RelativeLayout>
Activity Code:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MyActivity extends Activity implements View.OnClickListener{
private Button upBtn;
private Button downBtn;
private Button leftBtn;
private Button rightBtn;
private ImageView ballImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_my);
init();
}
public void init(){
ballImage = (ImageView)findViewById(R.id.ballImage);
upBtn = (Button) findViewById(R.id.upBtn);
upBtn.setOnClickListener(this);
downBtn = (Button) findViewById(R.id.downBtn);
downBtn.setOnClickListener(this);
leftBtn = (Button) findViewById(R.id.leftBtn);
leftBtn.setOnClickListener(this);
rightBtn = (Button) findViewById(R.id.rightBtn);
rightBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.upBtn:{
Toast.makeText(this,"UP",Toast.LENGTH_SHORT).show();
int[] locations = new int[2];
ballImage.getLocationOnScreen(locations);
ballImage.setX(locations[0]);
ballImage.setY(locations[1]-1);
Log.i("COORD X","X: "+locations[0]);
Log.i("COORD Y","Y: "+locations[1]);
break;
}
case R.id.downBtn:{
Toast.makeText(this,"DOWN",Toast.LENGTH_SHORT).show();
int[] locations = new int[2];
ballImage.getLocationOnScreen(locations);
ballImage.setX(locations[0]);
ballImage.setY(locations[1]+1);
Log.i("COORD X","X: "+locations[0]);
Log.i("COORD Y","Y: "+locations[1]);
break;
}
case R.id.leftBtn:{
Toast.makeText(this,"LEFT",Toast.LENGTH_SHORT).show();
int[] locations = new int[2];
ballImage.getLocationOnScreen(locations);
ballImage.setX(locations[0]-1);
Log.i("COORD X","X: "+locations[0]);
Log.i("COORD Y","Y: "+locations[1]);
break;
}
case R.id.rightBtn:{
Toast.makeText(this,"RIGHT",Toast.LENGTH_SHORT).show();
int[] locations = new int[2];
ballImage.getLocationOnScreen(locations);
ballImage.setX(locations[0]+1);
Log.i("COORD X","X: "+locations[0]);
Log.i("COORD Y","Y: "+locations[1]);
break;
}
}
}
}
The final result:
I used as image the default icon.
I can't understand why I'm getting this error message. My method IS in the activity class and the spelling is correct.
02-09 18:23:57.211: E/AndroidRuntime(19939): FATAL EXCEPTION: main
02-09 18:23:57.211: E/AndroidRuntime(19939): Process: stacy.example.assignment3_stacy_v1, PID: 19939
02-09 18:23:57.211: E/AndroidRuntime(19939): java.lang.IllegalStateException: Could not find a method startRhythmandAnimation(View) in the activity class stacy.example.assignment3_stacy_v1.Assignment3MainActivity for onClick handler on view class android.widget.Button with id 'startbutton'
MainActivity.java
package stacy.example.assignment3_stacy_v1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
public class Assignment3MainActivity extends Activity {
private View mMileTimeGoal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assignment3_main);
mMileTimeGoal = findViewById(R.id.miletimegoal);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.assignment3_main, menu);
return true;
}
public void startRhythmandAnimation () {
String MileTime = mMileTimeGoal.getContext().toString();
String[] time_array = MileTime.split(":");
int hours = Integer.parseInt(time_array[0]);
int minutes = Integer.parseInt(time_array[1]);
int seconds = Integer.parseInt(time_array[2]);
int duration = 3600 * hours + 60 * minutes + seconds;
int steps_per_second = 3;
int running_rate = duration * steps_per_second;
View rightfoot = findViewById(R.id.rightfoot);
View leftfoot = findViewById(R.id.leftfoot);
rightfoot.setVisibility(View.VISIBLE);
Animation anim = AnimationUtils.makeInChildBottomAnimation(this);
rightfoot.startAnimation(anim);
leftfoot.setVisibility(View.VISIBLE);
leftfoot.startAnimation(anim);
}
public void resetTimetoZeroes () {
String MileTime = mMileTimeGoal.getContext().toString();
//Int MileTime = 0;
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Assignment3MainActivity" >
<ImageView
android:id="#+id/leftfoot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/rightfoot"
android:layout_toLeftOf="#+id/rightfoot"
android:src="#drawable/leftfoot" />
<EditText
android:id="#+id/miletimegoal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:ems="10"
android:inputType="time"
android:hint="Mile Time Goal?" />
<ImageView
android:id="#+id/rightfoot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="74dp"
android:layout_marginRight="36dp"
android:src="#drawable/rightfoot" />
<Button
android:id="#+id/startbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/leftfoot"
android:layout_alignRight="#+id/leftfoot"
android:onClick="startRhythmandAnimation"
android:text="#string/start_button" />
<Button
android:id="#+id/resetbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/startbutton"
android:layout_alignBottom="#+id/startbutton"
android:layout_alignLeft="#+id/rightfoot"
android:text="#string/reset_button"
android:onClick="resetTimetoZeroes" />
You need to include a single View parameter for the system to find your method:
public void startRhythmandAnimation (View view)
I am developing a code breaking game i.e. Bulls and Cows in android. The problem is that in my main class I have applied a logic to check the numbers. This logic falls under a loop but when i run the application it freezes after entering into the loop. I'm tired of searching the answer on internet. I would be grateful to you people here if you could help out in some way. I regret if my code look lame to you as I'm a beginner in android programming.
The following is the code of my main class. :-
package com.bullsncows.bnc;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Startingpoint extends Activity {
EditText etn1, etn2, etn3, etn4;
Button bsub;
TextView errormsg,res;
Random r = new Random();
int num = 0;
boolean guessed = false;
int count =0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
initializevar();
// making the computer select a random four digit number
while(hasDupes(num= (r.nextInt(9000) + 1000)));
// on clicking the submit button
bsub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String n1 = etn1.getText().toString();
String n2 = etn2.getText().toString();
String n3 = etn3.getText().toString();
String n4 = etn4.getText().toString();
String cnum = num+"";
if (n1.length()==0||n2.length()==0||n3.length()==0||n4.length()==0) {
errormsg.setText("Fields cannot be left blank");
errormsg.setTextColor(Color.RED);
errormsg.setGravity(Gravity.CENTER);
} else if (n1.equals(n2) || n1.equals(n3) || n1.equals(n4)
|| n2.equals(n3) || n2.equals(n4) || n3.equals(n4)) {
errormsg.setText("Please enter distinct number");
errormsg.setTextColor(Color.RED);
errormsg.setGravity(Gravity.CENTER);
}else{
String guess = n1+n2+n3+n4;
errormsg.setText("Correct "+ cnum + " "+ guess);
errormsg.setTextColor(Color.GREEN);
errormsg.setGravity(Gravity.CENTER);
do{
int bulls = 0;
int cows = 0;
count++;
for(int i= 0;i < 4;i++){
if(guess.charAt(i) == cnum.charAt(i)){
bulls++;
}else if(cnum.contains(guess.charAt(i)+"")){
cows++;
}
else if(bulls == 4){
guessed = true;
break;
}else{
res.setText(cows+" Cows and "+bulls+" Bulls.");
res.setTextColor(Color.BLUE);
res.setGravity(Gravity.CENTER);
}
}
}while(!guessed);
errormsg.setText("You won after "+count+" guesses!");
errormsg.setTextColor(Color.MAGENTA);
errormsg.setGravity(Gravity.CENTER);
}
}
});
}
private void initializevar() {
// TODO Auto-generated method stub
etn1 = (EditText) findViewById(R.id.etnum1);
etn2 = (EditText) findViewById(R.id.etnum2);
etn3 = (EditText) findViewById(R.id.etnum3);
etn4 = (EditText) findViewById(R.id.etnum4);
bsub = (Button) findViewById(R.id.bsubmit);
errormsg = (TextView) findViewById(R.id.tverror);
res = (TextView) findViewById(R.id.tvres);
}
public static boolean hasDupes(int n){
boolean[] digs = new boolean[10];
while(n > 0){
if(digs[n%10]) return true;
digs[n%10] = true;
n/= 10;
}
return false;
}
}
The following is the XML coding for the same page :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Please select the numbers below" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<EditText
android:id="#+id/etnum1"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum2"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum3"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum4"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:id="#+id/tverror"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<TextView android:id="#+id/tvres"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/bsubmit"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="fill_vertical"
android:text="Submit" />
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</TableLayout>
</LinearLayout>
without reading all of your code, i seems very unlikely
else if(bulls == 4)
will ever evalute to true, since you reset bulls each iteration
int bulls = 0;
and you only have four tries:
for(int i= 0;i < 4;i++)
Since
else if(bulls == 4){
guessed = true;
break;
is your only termination condition, you loop forever.
If you could narrow down your code to just the area that is causing problems that will help. But I might guess that the loop that has an error is
while(n > 0){
n/= 10;
}
n might never get to 0. Can you step through your code and work out exactly which part is failing?