I have a basic hangman game, and the buttons to make the guesses are all placed on screen with ImageButtons (I had this working perfectly).
I declare the image button ID's like so:
private static final int[] BUTTON_IDS = {
R.id.imageButtonA, R.id.imageButtonB, R.id.imageButtonC, R.id.imageButtonD, R.id.imageButtonE,
R.id.imageButtonF, R.id.imageButtonG, R.id.imageButtonH, R.id.imageButtonI, R.id.imageButtonJ,
R.id.imageButtonK, R.id.imageButtonL, R.id.imageButtonM, R.id.imageButtonN, R.id.imageButtonO,
R.id.imageButtonP, R.id.imageButtonQ, R.id.imageButtonR, R.id.imageButtonS, R.id.imageButtonT,
R.id.imageButtonU, R.id.imageButtonV, R.id.imageButtonW, R.id.imageButtonX, R.id.imageButtonY, R.id.imageButtonZ
};
private List<ImageButton> buttonLetters = new ArrayList<ImageButton>();
Edited to show solution: I register their OnClick by doing:
for (int id: BUTTON_IDS) {
final ImageButton buttonLettersUsage = (ImageButton)findViewById(id);
if (buttonLetters != null) {
assert buttonLettersUsage != null;
buttonLettersUsage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HangmanActivity.this, " " + buttonLettersUsage.getId(), Toast.LENGTH_SHORT).show();
switch (buttonLettersUsage.getId()){
case R.id.imageButtonQ:
strGuessed = "Q";
break;
case R.id.imageButtonW:
strGuessed = "W";
break;
case R.id.imageButtonE:
strGuessed = "E";
break;
// ... Repeat for rest of buttons ...
default:
break;
}
btnGuessClicked(theIncorrectGuesses, theWord);
buttonLettersUsage.setVisibility(View.INVISIBLE);
}
});
}
}
The problem is now, I've been working on the app some more since implementing this part, and all the buttonLettersUsage.getId()'s have changed.
My question is:
Will they change at any time?
I've not put any new components onto the activity, why have they changed?
Is there a better way to find out which button has been pressed, and give a different value for strGuessed depending on which has been pressed?
Many thanks.
Don't use the numerical ids in the switch case use it as follows.
switch (buttonLettersUsage.getId()){
case R.id.imageButtonA:
strGuessed = "Q";
break;
case R.id.imageButtonB:
strGuessed = "W";
break;
case R.id.imageButtonC:
strGuessed = "E";
break;
// ... Repeat for rest of buttons ...
default:
break;
}
And also don't implement onClickListener like this, use your Activity to implement View.OnClickListener and then set the listener in loop as
buttonLettersUsage.setOnClickListener(this);
Where this is the context of your activity which implements the OnClickListener
YourActivity implements View.OnClickListener{
then in oncreate(){
//add is buton
View buttonAdd = findViewById(R.id.add);
buttonAdd.setOnClickListener(this);}
then
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
{
}
break;}
Related
Like this https://androidexample365.com/content/images/2019/05/OtpEditText.gif
if wordbox1.setText("C") get clicked wordbox1 become invisible and matchbox1.getText("C") when matchbox1 get clicked wordbox1 become visible and matchbox1.getText(null)
I want check if matchbox1 , matchbox2 ,matchbox3 = getText(null) to fill who null
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//my answer buttons
//if you click on any button of my question buttons look for
// who is null first of my answer buttons
Button matchbox1,matchbox2,matchbox3;
//my question buttons wordbox1 = "C" wordbox2 = "A" wordbox3 = "R"
// car is the correct answer
Button wordbox1,wordbox2,wordbox3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
matchbox1= (Button)findViewById(R.id.matchbox1);
matchbox2= (Button)findViewById(R.id.matchbox2);
matchbox3= (Button)findViewById(R.id.matchbox3);
wordbox1= (Button)findViewById(R.id.wordbox1);
wordbox2= (Button)findViewById(R.id.wordbox2);
wordbox3= (Button)findViewById(R.id.wordbox3);
//for example if matchbox1.getText(R) wordbox3.setVisibility(View.Visible);
matchbox1.setOnClickListener(this);
//for example if matchbox2.getText(A) wordbox2.setVisibility(View.Visible);
matchbox2.setOnClickListener(this);
//for example if matchbox3.getText(C) wordbox1.setVisibility(View.Visible);
matchbox3.setOnClickListener(this);
wordbox1.setOnClickListener(this);
wordbox2.setOnClickListener(this);
wordbox3.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.wordbox1:
matchbox1.setText("C");
wordbox1.setVisibility(View.INVISIBLE);
break;
case R.id.wordbox2:
matchbox2.setText("A");
wordbox2.setVisibility(View.INVISIBLE);
break;
case R.id.wordbox3:
matchbox3.setText("R");
wordbox3.setVisibility(View.INVISIBLE);
break;
//for example any button pressed
case R.id.matchbox1:
wordbox3.setVisibility(View.VISIBLE);
matchbox1.setText("");
break;
case R.id.matchbox2:
wordbox2.setVisibility(View.VISIBLE);
matchbox2.setText("");
break;
case R.id.matchbox3:
wordbox1.setVisibility(View.VISIBLE);
matchbox3.setText("");
break;
}
if (matchbox1.getText().toString().equals("C") &&
matchbox2.getText().toString().equals("A")&&
matchbox3.getText().toString().equals("R")){
matchbox1.setBackgroundColor(Color.GREEN);
matchbox2.setBackgroundColor(Color.GREEN);
matchbox3.setBackgroundColor(Color.GREEN);
}
}
}
I hope i find the answer becase I need it very much
I have a few interesting question here about how to return to latest activity if the game was restart/re-open because I have a new game button and continue button.So when continue button clicked it will return to last activity that opened before and the condition is activity is random from activityone to activityfive
I will explain with my code
this is menu.class
public class menu extends Activity {
int level;
Button newgame, continues, continuelocked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.menu);
continuelocked=(Button)findViewById(R.id.buttoncontinuelocked);
continues=(Button)findViewById(R.id.buttoncontinue);
newgame=(Button)findViewById(R.id.buttonnewgame);
newgame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i =new Intent(menu.this, intro.class);
startActivity(i);
}
});
}
public void onResume() {
super.onResume();
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
level = pref.getInt("Level", 0);
if(level == 0)
{
continuelocked.setVisibility(View.VISIBLE);
continues.setVisibility(View.GONE);
}
if(level == 1)
{
continuelocked.setVisibility(View.GONE);
continues.setVisibility(View.VISIBLE);
}
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", level);
editor.commit();
continues=(Button)findViewById(R.id.buttoncontinue);
continues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//How to set this method to return to latest activity that i play before
//if i use random levelactivity?
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and in intro.class I do this method to make activity random,
check my code below here -
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button5 = (Button)findViewById(R.id.button5);
if(v==button5) {
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", 1);
editor.commit();
// Here, we are generating a random number
Random generator = new Random();
int number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
and in every Activity "One to Five" I put the same random activity code
#Override
public void onClick(View v) {
// Here, we are generating a random number
Random generator = new Random();
int number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
}
So My question is
First. How to open the last Activity with a Continue button if Activity was Random?
Second. if in every Activity had a same Random code to One until Five, How to set Disabled to Activity that already Opened before?
Anyone can explain about this?
UPDATED
I have found a solution with my second answer, but i dont try it yet so i dont know it work or not
so i changed the code like this
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
button5 = (Button)findViewById(R.id.button5);
if(v==button5) {
SharedPreferences pref = getSharedPreferences("SavedGame", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("Level", 1);
editor.commit();
layout7.setVisibility(View.GONE);
layout7.setVisibility(View.VISIBLE);
// Here, we are generating a random number
Random generator = new Random();
number = generator.nextInt(5) + 1;
// The '5' is the number of activities
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
// E.g., if the output is 1, the activity we will open is ActivityOne.class
case 1: if(one == 1){
activity = ActivityOne.class;
}
else if(one == 2){
Random generatorone = new Random();
number = generatorone.nextInt(5) + 1;
}
break;
case 2: if(two== 1){
activity = ActivityTwo.class;
}
else if(two== 2){
Random generatortwo = new Random();
number = generatortwo.nextInt(5) + 1;
}
break;
case 3:if(three== 1){
activity = ActivityThree.class;
}
else if(three== 2){
Random generatorthree = new Random();
number = generatorthree.nextInt(5) + 1;
}
break;
case 4:if(four == 1){
activity = ActivityFour.class;
}
else if(four == 2){
Random generatorFour = new Random();
number = generatorFour.nextInt(5) + 1;
}
break;
default:if(five== 1){
activity = ActivityFive.class;
}
else if(five== 2){
Random generatorfive = new Random();
number = generatorfive.nextInt(5) + 1;
}
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
startActivity(intent);
}
};
i think, if the int was show ==2 its mean the Activity was already opened before. so it will random again till found activity with ==1
can anyone correct my code above? it is right or not?
and my first question still dont have an answer
First. How to open the last Activity with a Continue button if Activity was Random and the app was re-open/restart?
Thank you in advance, have a good day
For your first question, once you open your random Activity you can use SharedPreferences to store an ID for that Activity, and once you press your continue button, you can read this preferences, get this ID, and open the respective Activity.
For example, create an utility class to handle the SharedPreferences.
public class ActivityManager {
private static ActivityManager instance = null;
private SharedPreferences sharedPref;
private Context context_;
private final String prefName = "preferencesHandler";
public static ActivityManager getInstance(Context context) {
if (instance == null) {
instance = new ActivityManager(context);
}
return instance;
}
private ActivityManager(Context context) {
context_ = context;
sharedPref = context_.getSharedPreferences(prefName,Context.MODE_PRIVATE);
}
public void saveActivity(int ID) {
editor = sharedPref.edit();
// Key,Value
editor.putInt("activity_id",ID);
editor.commit();
}
public int getActivityID() {
// Key, Default Value
return sharedPref.getInt("activity_id",0);
}
}
And once you open each one of your random Activity, set some ID to them and save it using the class above. Then when needed, retrieve that value with getActivityID(). That should do the trick.
For more info on how to use SharedPreferences, please read this link.
EDIT: On your specific case, there's this part of your code:
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// E.g., if the output is 1, the activity we will open is ActivityOne.class
activity = ActivityOne.class;
break;
case 2:
activity = ActivityTwo.class;
break;
case 3:
activity = ActivityThree.class;
break;
case 4:
activity = ActivityFour.class;
break;
default:
activity = ActivityFive.class;
break;
}
You can easily use that number variable as an ID. So, once you randomly get that number, you can also save it using the SharedPreferences. And when you press the continue Button, simply read that value and use a switch-case again to get the correct Activity.
I have programmatically added a Linear Layout in Android and added ImageViews to it. I used the following code for the same.
LinearLayout layout = (LinearLayout)findViewById(R.id.linear1);
for(int i=0;i<4;i++)
{
imagev = new ImageView(this);
imagev.setLayoutParams(new android.view.ViewGroup.LayoutParams(300,150));
imagev.setMaxHeight(600);
imagev.setMaxWidth(600);
layout.addView(imagev);
}
If i were to implement this, i would give each of the imageviews a specific tag, and then set the same onClickListener to each imageview. Then in the onClickListener, i would check the tag for the imageview that was clicked and do an action depending on whatever imageview was clicked.
LinearLayout layout = (LinearLayout)findViewById(R.id.linear1);
for(int i=0;i<4;i++)
{
imagev = new ImageView(this);
imagev.setLayoutParams(new android.view.ViewGroup.LayoutParams(300,150));
imagev.setMaxHeight(600);
imagev.setMaxWidth(600);
imagev.setTag(i);
imagev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(Integer.valueOf(v.getTag())) {
case 0: ...
break;
case 1: ...
break;
}
}
layout.addView(imagev);
}
This would avoid having to have 4 different onClickListener, and give you some cleaner code.
You can do something like this:
myClickListener1 = new View.OnClickListener ...
myClickListener2 ...
myClickListener3 ...
myClickListener4 ...
for(int i=0;i<4;i++)
{
imagev = new ImageView(this);
imagev.setLayoutParams(new android.view.ViewGroup.LayoutParams(300,150));
imagev.setMaxHeight(600);
imagev.setMaxWidth(600);
switch(i){
case 0: imagev.setOnClickListener(myClickListener1);
break;
case 1: ...
...
}
layout.addView(imagev);
}
I have 20 XML layouts. What I want to happen is to show random xml layouts when the button is clicked. I tried and read same problem as mine but i didnt worked.
For example in Level1 class when the user clicked the PositiveButton in the AlertDialog, random XML Layout will be opened (Level 20 or Level 15 not Level 2).
This is code in Level1 class(the same pattern applies for the rest of the classes)
public class Luzon1 extends Activity {
private String [] answers;
private Button answerButton;
private TextView scoreTxt, showClue;
private EditText answerText;
int scoreNew=0;
public Button yes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_luzon1);
}
public void init()
{
//correct answer
answers=new String[]{"Tarlac"};
(R.id.AnswerButton);
answerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
checkAnswer();
}
});
}
public boolean isCorrect(String answer)
{ return(answer.equalsIgnoreCase(answers[currentQuestion])); }
public void checkAnswer()
{ String answer=answerText.getText().toString();
if(isCorrect(answer))
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Congratulations! You will receive P10!");
builder.setMessage("Did you know that Former bla bla bla Did you know that Former bla bla bla Did you know that Former bla bla bla");
builder.setIcon(android.R.drawable.btn_star_big_on);
builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String userData=scoreTxt.getText().toString();
int userNumber=Integer.parseInt(userData);
Intent intent=new Intent(Luzon1.this, Luzon2.class);
intent.putExtra("parameter name", userNumber);
startActivity(intent);
Luzon1.this.finish(); System.exit(0);
} });
AlertDialog alert = builder.create();
alert.show(); // Show Alert Dialog
Thank you so much in advance. and any code snippet will be a great help.
Setting the layout from inside onClick()
If you want this code to be in the onClick() method in your previous activity (the one shown above), use the following code:
#Override
protected void onClick(DialogInterface dialog, int which) {
Random generator = new Random();
int number = generator.nextInt(NUMBER_OF_LEVELS) + 1;
Class activity;
switch(number) {
case 1:
activity = LevelOne.class;
break;
case 2:
activity = LevelTwo.class;
break;
case 3:
activity = LevelThree.class;
break;
case 4:
activity = LevelFour.class;
break;
case 5:
activity = LevelFive.class;
break;
...
case 20:
activity = LevelTwenty.class;
break;
}
Intent intent = (getBaseContext(), activity);
startActivity(intent);
}
Try this:
Declare a public static int count = 0 before onCreate..
then, In onClick increment the count by 1(count++)..
Use switch statement like,(Dont forget to reset counter to 0 when count becomes 20)
void onClick(){
count++;
switch(count) {
case 1:
setContentView(R.layout.yourLayout1);
break;
case 2:
setContentView(R.layout.yourLayout2);
break;
case 3:
setContentView(R.layout.yourLayout3);
break;
case 4:
setContentView(R.layout.yourLayout4);
................................
................................
case 20:
setContentView(R.layout.yourLayout20);
break;
}
if(count==20){
count = 0;
}
}
And also instead of incrementing count each time user clicks, you can use Math.random() and assign it to count (Remember to check(use if statement) Math.random() is returning a value which is below or equal to 20..)
Hope it will help you..
I am trying to reduce the amount of code I have by making everything more efficient
I want to implement a switch statement instead of a long if statement
here is the switch i have began creating
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonA:
displayLetters(v);
break;
case R.id.buttonB:
displayLetters(v);
break;
and here is the displayLetters method that I want each case to run
private void displayLetters(View v) {
NewDisplayWord = EditText.getText().toString();
NewDisplayWord = NewDisplayWord + v.getTag();
EditText.setText(NewDisplayWord);
}
However instead of displaying A or B in the textedit when I press the buttons, I get null when I press any of the buttons
It seems that you are trying to get the text from the EditText by doing EditText.getText(). I think what you mean to do is use the v variable passed into displayLetters(). You can do something like this:
private void displayLetters(View v) {
NewDisplayWord = ((EditText)v).getText().toString();
NewDisplayWord = NewDisplayWord + v.getTag();// I do not know what is the use of `getTag()` here...
((EditText)v).setText(NewDisplayWord);
}
If the displayLetters() will only deal with EditTexts, you can make its parameter be an EditText
First, let's change displayLetters to accept String
private void displayLetters(final String letter) {
newDisplayWord = editText.getText().toString();
newDisplayWord = newDisplayWord + letter;
editText.setText(newDisplayWord);
}
Then call displayLetters() with String param:
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonA:
displayLetters(v.getTag());
break;
case R.id.buttonB:
displayLetters(v.getTag());
break;
default:
break;
}
}
If your onClick() listener will serve only the buttons, you could probably simplify it even further:
#Override
public void onClick(View v) {
//cast view to button
Button bt = (Button) v;
//get text from button
final String letter = bt.getText().toString();
//pass it to displayLetters()
displayLetters(letter);
}
Please follow Java naming convention, that is variable names start with lowercase. Also, I'm assuming that you have properly set your button and editText:
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);