Shuffling images with buttons matching the shuffle - java

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;
}

Related

grid layout android studio

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

Setting different text of a textview from an arraylist

I have a textview created programmatically in a loop. On a click of a button i want to fill each textview created with different values from the array how do i achieve this. Here is what happens when the button is clicked. Thanks for the help.
btnPnar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listLayout.removeAllViews();
for (EditText et : editTextCollection)
{
gottenText = et.getText().toString();
inputList.add(gottenText);
Collections.shuffle(inputList);
}
// Creating alert Dialog with one Button
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,R.style.DialogeTheme);
// Setting Dialog Title
alertDialog.setTitle("PNAR");
// Setting Dialog Message
alertDialog.setMessage("Enter Amount of Numbers to Pick");
final EditText input; input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setTextColor(Color.parseColor("#f06292"));
input.setInputType(2);
alertDialog.setView(input);
alertDialog.setPositiveButton("DONE",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
pnarGotten = Integer.parseInt(input.getText().toString());
Collections.shuffle(inputList);
for (int n =0; n<pnarGotten; n++) {
TextView textView = new TextView(MainActivity.this);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setText(inputList.get(0));
textView.setText(inputList.get(1));
listLayout.addView(textView);
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.create();
alertDialog.show();
}
});
UPDATE
This is what i added to the code inside the for loop but it shows only one output
for (int n =0; n<pnarGotten; n++) {
textViewForPnar = new TextView(MainActivity.this);
textViewForPnar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textViewForPnar.setGravity(Gravity.CENTER);
textViewForPnar.setTextColor(Color.WHITE);
while (iterator.hasNext())
{
textViewForPnar.setText(iterator.next());
}
listLayout.addView(textViewForPnar);
}
You should use Iterator object of your inputList collection to retvieve elements from it:
Iterator<String> iterator = inputList.iterator();
while (iterator.hasNext())
{
textView.setText(iterator.next());
}
Just simply replace your for loop with this code
for (int n = 0; n < pnarGotten; n++)
{
TextView textView = new TextView(MainActivity.this);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(Color.WHITE);
textView.setText(inputList.get(n));
listLayout.addView(textView);
}

Setting Button text programmatically is automatically going to last Index

So I'm working on an Android app, and trying to add buttons that will have click-triggered Dialogs programmatically.
When I add the OnClickListener to these buttons, I'm either getting the text from the last Button added, an error claiming that there is an IOOBException when calling tv1.setText(...) - invalid index 7, size is 7, or just nothing passed. Does anybody have any idea how I can set each Button to create a new Dialog with unique information for each button?
Snippet of code that's posing the problem:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
prefs = getSharedPreferences("carter.streakly", Context.MODE_PRIVATE);
editor = prefs.edit();
db = new DatabaseHelper(this);
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
res = db.getAllData();
if(res.getCount() ==0) {
//show message
showMessage("Error", "Nothing found");
return;
}
streakArrayList = new ArrayList<>();
int counter = 0;
while (res.moveToNext()){
streakArrayList.add(new Streak(Integer.parseInt(res.getString(0)), res.getString(1), res.getString(2), res.getString(3), Integer.parseInt(res.getString(4))));
counter++;
}
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(200, 200);
btnParams.setMargins(200, 30, 80, 30);
LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
tvParams.setMargins(100, 0, 0, 0);
i = 0;
while (i < counter){
if(i%2==0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
mTableRow.addView(ll);
Button btn = new Button(this);
btn.setText(""+streakArrayList.get(i).getDaysKept());
btn.setId(i);
btn.setBackground(getResources().getDrawable(R.drawable.round_button));
btn.setLayoutParams(btnParams);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dialog dialog = new Dialog(AllStreaks.this);
dialog.setContentView(R.layout.activity_enlarged);
tv1 = (TextView) dialog.findViewById(R.id.activity_enlarge_icon);
tv1.setText(streakArrayList.get(i-1).getActivityName());
dialog.show();
/*
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
intent.putExtra("passName", streakArrayList.get(view.getId()).getActivityName());
startActivity(intent);*/
}
});
ll.addView(btn);
TextView tv = new TextView(this);
tv.setText(streakArrayList.get(i).getActivityName());
tv.setId(i);
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setTextSize(20);
tv.setLayoutParams(tvParams);
ll.addView(tv);
i++;
}
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
There are many problems with your code.
First of all, you're using a global instance of both your TableRow and LinearLayout. This means you overwrite them on every iteration of your loop, so in the end only the values from the last iteration will be visible.
You're giving the same ID to both your Button and your TextView, they should be unique.
Using the counter variable is completely unnecessary, you could just use a for loop to iterate through your streakArrayList.
Something like this:
for (Streak streak : streakArrayList) {
TableRow mTableRow = new TableRow(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final String activityName = streak.getActivityName();
Button btn = new Button(this);
btn.setText("" + streak.getDaysKept());
btn.setId(aUniqueId);
btn.setBackground(getResources().getDrawable(R.drawable.round_button));
btn.setLayoutParams(btnParams);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dialog dialog = new Dialog(AllStreaks.this);
dialog.setContentView(R.layout.activity_enlarged);
tv1 = (TextView) dialog.findViewById(R.id.activity_enlarge_icon);
tv1.setText(activityName);
dialog.show();
}
});
TextView tv = new TextView(this);
tv.setText(activityName);
tv.setId(anotherUniqueId);
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setTextSize(20);
tv.setLayoutParams(tvParams);
ll.addView(btn);
ll.addView(tv);
mTableRow.addView(ll);
mTableLayout.addView(mTableRow);
}

Android shuffle button position onClick

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.

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

Categories