I have 6 buttons and I'm trying to shuffle their position when any button is clicked.
The first shuffle (when the activity is started) is done by: Collections.shuffle(buttonList);
How do I shuffle when any of the buttons is clicked?
Java:
public class Main extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
LinearLayout ll = (LinearLayout) findViewById(R.id.llShuffleBox);
LinearLayout top_layout = (LinearLayout) findViewById(R.id.top_layout);
LinearLayout middle_layout = (LinearLayout) findViewById(R.id.middle_layout);
final ArrayList<Button> buttonList = new ArrayList<Button>();
for(int i=0; i<6; i++) {
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(i + 1);
buttonList.add(b);
}
//First shuffle
Collections.shuffle(buttonList);
for (int i = 0; i<6; i++) {
if (i <3) {
top_layout.addView(buttonList.get(i));
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
}
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Main">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llShuffleBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="50dp">
<LinearLayout
android:id="#+id/top_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
</LinearLayout>
<LinearLayout
android:id="#+id/middle_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
First move the initial setup of the buttons to the onCreate method.
private LinearLayout top_layout;
private LinearLayout middle_layout;
private final ArrayList<Button> buttonList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
top_layout = (LinearLayout) findViewById(R.id.top_layout);
middle_layout = (LinearLayout) findViewById(R.id.middle_layout);
for(int i=0; i<6; i++) {
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(i + 1);
b.setOnClickListener(clickListener);
buttonList.add(b);
}
shuffleButtons();
}
Then put the code to remove button views, shuffle them, then re-add in a method.
private void shuffleButtons() {
top_layout.removeAllViews();
middle_layout.removeAllViews();
Collections.shuffle(buttonList);
for (int i = 0; i<6; i++) {
if (i <3) {
top_layout.addView(buttonList.get(i))
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
Also attach a click listener to each of the buttons that will call through to the shuffle method.
private View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
shuffleButtons();
}
}
Consider: Instead of shuffling the buttons change the numbers on them, that way you don't have to re-layout your app and move the buttons around.
If you are set on shuffling the buttons the easiest way is to remove them and add them back in the new order.
To get the event when you click on a button you register an onClickListener, the code for that could look like this:
class YourClass implements OnClickListener
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setOnClickListener (this)
public void onClick(View view) {
shuffle();
}
Try something like this
public class Main extends AppCompatActivity implements OnClickListener{
private Button b1, b2, b3, b4, b5, b6;
private ArrayList<Button> buttonList = new ArrayList<Button>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0; i<6; i++) {
final Button b = new Button(this);
b.setText("" + (i + 1));
b.setGravity(Gravity.CENTER_HORIZONTAL);
b.setId(i + 1);
buttonList.add(b);
}
b1 = (Button) findViewById(...);
b2 = (Button) findViewById(...);
b3 = (Button) findViewById(...);
b4 = (Button) findViewById(...);
b5 = (Button) findViewById(...);
b6 = (Button) findViewById(...);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
LinearLayout ll = (LinearLayout) findViewById(R.id.llShuffleBox);
LinearLayout top_layout = (LinearLayout) findViewById(R.id.top_layout);
LinearLayout middle_layout = (LinearLayout) findViewById(R.id.middle_layout);
//First shuffle
Collections.shuffle(buttonList);
for (int i = 0; i<6; i++) {
if (i <3) {
top_layout.addView(buttonList.get(i));
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
#Override
public void onClick(View v) {
Collections.shuffle(buttonList);
}
}
Replace the ... for their respective layout ids.
Just after b.setId(i+1); add this code -
b.setId(i + 1); //this line you already have add these after
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(buttonList);
for (int i=0; i<6; i++){
//removing the buttons from the view
ViewGroup layout = (ViewGroup) buttonList.get(i).getParent();
if (null != layout) //for safety only as you are doing onClick
layout.removeView(buttonList.get(i));
}
for (int i = 0; i<6; i++) {
//adding the buttons again
if (i <3) {
top_layout.addView(buttonList.get(i));
} else {
middle_layout.addView(buttonList.get(i));
}
}
}
});//end of onClickListener; this is all which you have to add;
buttonList.add(b);//this line you already have
}
This is all. It should do exactly what you want now.
Related
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
I want to create dynamic RadioGroup (with dynamic radio options). I'm doing with the following code.
My question is that, how can I get the option that is selected by clicking the button "Check Answer". If the radio group is added through the XML layout then I can get by its ID, but in this case I'm unable to do so.
Here's the code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="#+id/button">
</LinearLayout>
<TextView
android:id="#+id/answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/button"
android:textColor="#008b00"
/>
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check Answer"
app:layout_constraintBottom_toBottomOf="parent"
android:onClick="checkAnswer"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity:
package com.example.quiz8;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option...");
}
}
You can set a tag to the RadioGroup in order to be able to find it easily. A tag can be any Object. We'll use a String here, which has to be unique in the ViewGroup on which you call findViewWithTag(). Then in checkAnswer() you retrieve the RadioGroup by its tag and so get the text of the checked RadioButton.
private static final String RADIOGROUP_TAG = "radiogroup";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setTag(RADIOGROUP_TAG);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
RadioGroup radioGroup = linearLayout.findViewWithTag(RADIOGROUP_TAG);
int checkedId = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = radioGroup.findViewById(checkedId);
String text = radioButton.getText().toString();
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option..." + text);
}
Another option: you can have String[] title and the RadioGroup as fields in your Activity. This makes sense since you need them in more than one place.
private final String[] title = {"Male", "Female", "Other", "Secret"};
private RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
radioGroup = new RadioGroup(this);
RadioButton radioButton;
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
int checkedId = radioGroup.getCheckedRadioButtonId();
TextView answerText = (TextView) findViewById(R.id.answer);
// Note: make sure there is a checked RadioButton!
answerText.setText("You selected the option..." + title[checkedId]);
}
You can simply check for the selected one.
public class MainActivity extends AppCompatActivity {
private LinearLayout linearLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
RadioGroup radioGroup = new RadioGroup(this);
RadioButton radioButton;
final String[] title = {"Male", "Female", "Other", "Secret"};
for (int i = 0; i < title.length; i++) {
radioButton = new RadioButton(this);
radioButton.setId(i);
radioButton.setText(title[i]);
radioGroup.addView(radioButton);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//checkedId is the RadioButton selected
}
}
linearLayout.addView(radioGroup);
}
public void checkAnswer(View view) {
//get the answer here
TextView answerText = (TextView) findViewById(R.id.answer);
answerText.setText("You selected the option...");
}
}
1) You can add following code in OnClickListner() to check if desired check boxed is clicked.
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
Further help can be found in Radio button documentation : Radio Button Documentation
2) Another method: A better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
}
});
I have created an app which adds cards and a title is set on each card after taking a name input from user. In order to retain the cards and the title during app restart I am using sharedpreferences and saving the individual card titles in an array. The issue is after first app restart the card titles are retained but on further app restart the card titles are not retained. Although the number of cards are still retained.
public class MainActivity extends AppCompatActivity {
private CardView cardview;
private CardView cardview2;
private LinearLayout.LayoutParams layoutparams1;
private LinearLayout layout;
public SharedPreferences mSettings;
int mCount;
int i=0,j=0;
public TextView tv1;
public TextView tv4;
public TextView tv3;
String name;
String names[] = new String[10];
String key[] = {"A","B","C","D","F","G","H"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCount=0;
Button b1 = findViewById(R.id.button);
layout=findViewById(R.id.view);
tv1 = findViewById(R.id.textView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
names[mCount] = tv1.getText().toString().trim();
mCount++;
saveName();
}
});
}
private void saveName() //Cardview-1 function to
{
cardview = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview.setLayoutParams(layoutparams1);
cardview.setCardBackgroundColor(Color.WHITE);
cardview.setMinimumHeight(400);
tv3 = new TextView(getApplicationContext());
tv3.setText(tv1.getText().toString().trim());
cardview.setRadius(30);
cardview.addView(tv3);
layout.addView(cardview);
}
private void saveName2() //Cardview 2 function
{
cardview2 = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview2.setLayoutParams(layoutparams1);
cardview2.setCardBackgroundColor(Color.WHITE);
cardview2.setMinimumHeight(400);
tv4 = new TextView(getApplicationContext());
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
name = mSettings.getString(key[j],"");
tv4.setText(name);
j++;
cardview2.setRadius(30);
cardview2.addView(tv4);
layout.addView(cardview2);
}
#Override
public void onPause() {
super.onPause();
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mSettings.edit();
editor.putInt("COUNT_CARDS", mCount);
for(int i=0; i<mCount; i++)
editor.putString(key[i],names[i]);
editor.commit();
}
#Override
public void onResume() {
super.onResume();
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
if(mSettings.contains("COUNT_CARDS"))
{
mCount = mSettings.getInt("COUNT_CARDS", 0);
for (int i=0; i<mCount; i++)
saveName2();
}
}
}
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:layout_width="match_parent"
android:id="#+id/layout"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view"
android:orientation="vertical"
android:layout_marginTop="200dp"
android:background="#color/cardview_dark_background">
</LinearLayout>
<EditText
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="40dp" />
</RelativeLayout>
There is no need to store every card in onPause() method. We will only write new card in sharedPref as prev cards are already presen in sharedPref. So when you are trying to save the prev cards in the loop, there is a problem.( writing blank value).
public class MainActivity extends AppCompatActivity {
private CardView cardview;
private CardView cardview2;
private LinearLayout.LayoutParams layoutparams1;
private LinearLayout layout;
public SharedPreferences mSettings;
int mCount;
int i=0,j=0;
public TextView tv1;
public TextView tv4;
public TextView tv3;
String name;
String names[] = new String[10];
String key[] = {"A","B","C","D","F","G","H"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCount=0;
Button b1 = findViewById(R.id.button);
layout=findViewById(R.id.view);
tv1 = findViewById(R.id.textView);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
names[mCount] = tv1.getText().toString().trim();
mCount++;
saveName();
}
});
}
private void saveName() //Cardview-1 function to
{
cardview = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview.setLayoutParams(layoutparams1);
cardview.setCardBackgroundColor(Color.WHITE);
cardview.setMinimumHeight(400);
tv3 = new TextView(getApplicationContext());
tv3.setText(tv1.getText().toString().trim());
cardview.setRadius(30);
cardview.addView(tv3);
layout.addView(cardview);
saveInPref();
}
private void saveInPref() {
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mSettings.edit();
editor.putInt("COUNT_CARDS", mCount);
editor.putString(key[mCount-1],names[mCount-1]);
editor.apply();
}
private void saveName2() //Cardview 2 function
{
cardview2 = new CardView(getApplicationContext());
layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutparams1.setMargins(18, 30, 18, 0);
cardview2.setLayoutParams(layoutparams1);
cardview2.setCardBackgroundColor(Color.WHITE);
cardview2.setMinimumHeight(400);
tv4 = new TextView(getApplicationContext());
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
name = mSettings.getString(key[j],"");
tv4.setText(name);
j++;
cardview2.setRadius(30);
cardview2.addView(tv4);
layout.addView(cardview2);
}
#Override
public void onResume() {
super.onResume();
mSettings = getSharedPreferences("APP_PREFERENCES", Context.MODE_PRIVATE);
if(mSettings.contains("COUNT_CARDS"))
{
mCount = mSettings.getInt("COUNT_CARDS", 0);
for (int i=0; i<mCount; i++)
saveName2();
}
}
}
So when you click on the SAVE button then only you can save card in SharedPref. This will save in unnecessary write operation on sharedPref.
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
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;
}