grid layout android studio - java

I am trying to make an application that generates buttons with random color but I don't even know how to generate these buttons help!!
I have tried to do it with the manual that our teacher has offered us but it is incomplete
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public void onClick (View v){
if (v.getClass().getSimpleName().equals("Button")) {
Button b = (Button) v;
}
}
public void Recorrer () {
View v;
GridLayout g = (GridLayout) findViewById(R.id.grLayout);
for (int i = 0; i < g.getChildCount(); i++) {
v = g.getChildAt(i);
Button b;
if (v.getClass().getSimpleName().contains("Button")) {
b = (Button) v;
b.setOnClickListener(this);
}
Log.e("Objetito: ", v.getClass().getSimpleName() + "<--->" +
v.toString());
}
}
public void añadeHijos (){
GridLayout g = (GridLayout) findViewById(R.id.grLayout);
Button b;
int iden;
for (int i = 0; i < 18; i++) {
b = new Button(this);
b.setLayoutParams(new
ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
iden = View.generateViewId();
b.setId(iden);
b.setText("botón" + i);
g.addView(b, i);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

If randomly generate color or button try Math.random() and create array that contain colors and buttons text name. Try your luck here Adding Buttons

Related

Multiple random number results

Currently working in Android Studio and running into a little trouble. Trying to get my rollScore button to roll over and over. At this point it "rolls" once and stops. I've tried a for loop and while loop and unable to get it to allow multiple "rolls".
public class GameScreen extends AppCompatActivity {
private Button rollButton; // Roll button being declared as a variable
private TextView rollScore; // Text view being declared as a variable
private TextView totalSCore; //
private int mCounter = 0;
private int totalRuns = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
final int randomInt = randomGenerator.nextInt(7) + 1;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
}
You have to generate a new random number on each click on your button.
Like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
int randomInt;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
randomInt = randomGenerator.nextInt(7) + 1;
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
You need to generate a new random number after every roll e.g.
rollScore.setText(Integer.toString(randomGenerator.nextInt(7) + 1));

Random numbers to button

How can I put random numbers to button in Android studio with Java? Thank you beforehand.
I wanna put random numbers 4x4 button.
I tried this code but it shows Array list in button:
private LinearLayout container;
int[] ran={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
container = findViewById(R.id.container);
shuffleArray(ran);
for (int i = 0; i < container.getChildCount(); i++) {
LinearLayout row = (LinearLayout) container.getChildAt(i);
for (int j = 0; j < row.getChildCount(); j++) {
Button button = (Button) row.getChildAt(j);
button.setOnClickListener(this);
button.setText(Arrays.toString(ran));
button.setTextSize(24);
}
}
}
import java.util.*;
class IntasString{
public static void main(String args[]){
int min=1,max=15,result;
int myarr[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int range=(max-min)+1;
result=(int)(Math.random() * range) + min;
String indexValue=String.valueOf(myarr[result]);
System.out.println(indexValue);
}
}
Use this code according you and use variable indexValue to set text for Button

Android Program...coding Error

I want to print A,B,C..... in series, but when I click the button it's Unfortunately stopped,
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView alphabets = (TextView) findViewById(R.id.alphabet);
Button next = (Button) findViewById(R.id.button);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] alpha= {"A","B","C" ,"D" ,"E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int alp = alpha.length;
for (int i=0;i<=alpha.length;i++)
alphabets.setText(alpha[i]);
}
};
next.setOnClickListener(listener);
the reason is an IndexOutOfBoundException here:
for (int i=0;i<=alpha.length;i++)
alphabets.setText(alpha[i]);
}
change it to
for (int i=0;i<alpha.length;i++)
alphabets.setText(alpha[i]);
}
with your code you try to enter the last element +1 and that element does not exists.
btw. your textview will only display the last element!
EDIT:
String[] alpha= {"A","B","C" ,"D" ,"E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
int alp = alpha.length;
StringBuffer alphabet = new StringBuffer();
for (int i=0;i<alpha.length;i++){
alphabet.append(alpha[i]);
}
alphabets.setText(alphabet.toString());
Try this
String alpha[30];
alpha= {"A","B","C" ,"D" ,"E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

android dynamic button with setOnClickListener

I try to create dynamic buttons. When a button is clicked, the color of the button will change to red. When another one is clicked, the color of the previous button should be reset to the default color.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linear;
linear = (LinearLayout) findViewById(R.id.ly);
for (i = 1; i < 4; i++) {
final Button btn = new Button(this);
btn.setId(1000 + i);
btn.setBackgroundColor(Color.BLUE);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
linear.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
btn.setBackgroundColor(Color.RED);
}
});
}
How can I get the id of the non clicked button?
You can try this:
ArrayList<Button> mButtonList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linear;
linear = (LinearLayout) findViewById(R.id.ly);
for (int i = 1; i < 4; i++) {
final Button btn = new Button(this);
btn.setId(1000 + i);
btn.setBackgroundColor(Color.BLUE);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Button button : mButtonList) {
if (button.getId() == view.getId()) {
button.setBackgroundColor(Color.RED);
} else {
button.setBackgroundColor(Color.BLUE);
}
}
}
});
linear.addView(btn);
mButtonList.add(btn);
}
}
Add implements onClickListener to Your Activity and set this listener to you button in for loop like
valueB.setOnClickListener(this);
And Override the onClick method where you get button id
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "" + v.getId(), 800).show();
}
Once you get button id you can change text color

Shuffling images with buttons matching the shuffle

I am trying to layout 10 image buttons numbered 1-10 randomly on screen.
I used an array list and Collections. Shuffle command to shuffle the background drawables.
But I cant seem to tie the button listeners to these random images.
// assigned arrays here
Button[] buttons = new Button[10];
Button[] buttonimages = new Button[10];
List<Button> list;
// Global Variables
int[] buttonarray = {R.drawable.button1,R.drawable.button2,R.drawable.button3,R.drawable.button4,R.drawable.button5,R.drawable.button6,R.drawable.button7,R.drawable.button8,R.drawable.button9,R.drawable.button10};
int idarray[] = {R.id.number1,R.id.number2,R.id.number3,R.id.number4,R.id.number5,R.id.number6,R.id.number7,R.id.number8,R.id.number9,R.id.number10};
// then I add to arraylist and shuffle
public void randomnumbers2() {
for (int z=0;z<10;z++) {
buttons[z] = (Button)findViewById(idarray[z]);
}
for (int k=0;k<10;k++) {
buttonimages[k] = (Button)findViewById(buttonarray[k]);
}
list = new ArrayList<Button>(10);
for(int i = 0; i < 10; i++) list.add(buttons[i]);
Collections.shuffle(list);
for (int z=0;z<10;z++) {
buttons[z] = (Button)findViewById(idarray[z]);
}
for (int j=0;j<10;j++){
Button b1 = (Button) findViewById(idarray[j]);
((Button) list.set(j, buttons[j])).setBackgroundResource(buttonarray[j]);
}
}
But my buttons are defined like this:
setup buttons
button1 = (Button) findViewById(R.id.number1);
button2 = (Button) findViewById(R.id.number2);
button3 = (Button) findViewById(R.id.number3);
button4 = (Button) findViewById(R.id.number4);
button5 = (Button) findViewById(R.id.number5);
button6 = (Button) findViewById(R.id.number6);
button7 = (Button) findViewById(R.id.number7);
button8 = (Button) findViewById(R.id.number8);
button9 = (Button) findViewById(R.id.number9);
button10 = (Button) findViewById(R.id.number10);
Problem is,
when I click the first button. It has an image of number 5, in the 1st position, but its still associated with button #1. Basically I have 2 rows of 5 numbers mixed up. I want the button click to respond to button 5, not button1.
To get you started,
LinearLayout ll;
ArrayList<Button> buttons = new ArrayList<Button>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create a layout
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 10; i++) {
buttons.add(createButton(i));
}
Collections.shuffle(buttons);
for (Button b : buttons) {
ll.addView(b);
}
setContentView(ll);
}
private Button createButton(final int i) {
Button b = new Button(this);
b.setText(i + "");
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Clicking button: " + i, Toast.LENGTH_SHORT).show();
}
});
b.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
return b;
}
Here, I am just trying to create buttons and set index as the display text. You can set your background resources to pictures or whatever you would like to. Hope this helps.
To have 2 rows of 5 buttons, you will need three linear layouts. Here we go for the code...
LinearLayout ll;
ArrayList<Button> buttons = new ArrayList<Button>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create main layout which will host two linear layouts vertically
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
//create another two linear layouts which will host 5 buttons horizontally
Linear linearLayout1 = new LinearLayout(this);
Linear linearLayout2 = new LinearLayout(this);
for (int i = 0; i < 10; i++) {
buttons.add(createButton(i));
}
Collections.shuffle(buttons);
//add first 5 buttons to first layout
for (int i=0;i<5;i++) {
linearLayout1.addView(buttons.get(i));
}
//add remaining 5 to second layout
for (int i=5;i<10;i++){
linearLayout2.addView(buttons.get(i));
}
//add two layouts to main layout
ll.addView(linearLayout1);
ll.addView(linearLayout2);
//set main linear layout to be main layout of the actvitiy.
setContentView(ll);
}
private Button createButton(final int i) {
Button b = new Button(this);
b.setText(i + "");
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Clicking button: " + i, Toast.LENGTH_SHORT).show();
}
});
b.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
return b;
}

Categories