I have an array of button of size probably more than 20-30. My simple question is how to get the array index of the button that have been click? For example, i clicked btnDisplay[8] and then the apps will toast "8". As simple as that. but i don't know how to retrieve the index of the arrayed button.
switch (clickedButton.getId())
{
case R.id.Button01:
// do something
break;
case R.id.Button01:
// do something
break;
}
If i use this code, then i have to wrote like 20-30 cases. would there be a better solution?
How i generate button array
public class MainActivity extends Activity {
Button[] btnUpdate;
public void onCreate(Bundle savedInstanceState) {
//SOME CODE HERE
jsonParser = new JSONParser();
jObj = jsonParser.getJSONFromUrl(URL);
btnUpdate = new Button[jObj.length()];
for(int i=0;i<jObj.length();i++)
{
btnUpdate[i] = new Button(getApplicationContext());
btnUpdate[i].setText("Edit");
btnUpdate[i].setHeight(50);
}
Try this way
for (int i = 0; i < jObj.length(); i++) {
btnUpdate[i] = new Button(getApplicationContext());
btnUpdate[i].setText("Edit");
btnUpdate[i].setHeight(50);
btnUpdate[i].setTag(i); //ADD THIS LINE.
}
void onClick(View v) {
int index = (Integer) v.getTag();
Toast.makeText(getApplicationContext(), "BtnClicked"+index, Toast.LENGTH_SHORT).show();
}
Somehow try to use btnDisplay.indexof(); it works in C# I am not sure about Java
Try something like this
void onClick(View v)
{
int index = 0;
for (int i = 0; i < buttonArray.length; i++)
{
if (buttonArray[i].getId() == v.getId())
{
index = i;
Toast.makeText(getApplicationContext(), "BtnClicked"+index, Toast.LENGTH_SHORT).show();
break;
}
}
}
Related
I am trying to use a loop to set the action for each button when clicked (since most of the buttons will just return their text value), however I am getting an error stating "variable 'i' is accessed from within inner class, needs to be declared final". How can I get around this?
Here is what I got
String getValuesPressed(){
for(int i = 0; i < buttonList.length; i++){
buttonList[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(i == 0){//error occurs here
//do stuff
}
}
});
}
return textOnScreen;
}
You can copy the value of i in to a temp final variable as -
for (int i = 0; i < buttonList.length; i++) {
final int finalI = i;
buttonList[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalI == 0) {//error occurs here
//do stuff
}
}
});
}
You are creating an anonymous class (View.OnClickListener) for each button, the onClick() method within that class has a different scope than the method getValuesPressed(), therefore it has no access to local variable i.
The solution is contained within the link provided above:
An anonymous class cannot access local variables in its enclosing
scope that are not declared as final or effectively final.
Therefore introducing a final variable into the loop would resolve the error:
String getValuesPressed(){
for(int i = 0; i < buttonList.length; i++){
final int j = i;
buttonList[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(j == 0){//error occurs here
//do stuff
}
}
});
}
return textOnScreen;
}
You could create you own listener that takes the position as a parameter to workaround the fact you are using an anonymous inner class.
private class MyClickListener implements View.OnClickListener {
int position;
public MyClickListener (int position) {
this.position = position;
}
#Override
public void onClick(View v) {
if(position == 0){
//do stuff
}
}
}
Then in your loop you can create it like this
String getValuesPressed(){
for(int i = 0; i < buttonList.length; i++){
buttonList[i].setOnClickListener(new MyClickListener(i));
}
return textOnScreen;
}
This question already has answers here:
Get text from pressed button
(8 answers)
Closed 8 years ago.
How can i get the text set on the button inside the on-click() class?
i need to get the button text for sq l select statement
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is");
}
});
c.moveToNext() ;
enter code here
You can type caste the view to button and use it to getText().
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(),
Toast.LENGTH_SHORT).show();
Button b = (Button)v;
String buttonText = b.getText().toString();
Log.d("TAG", "The text is " + buttonText);
}
});
c.moveToNext() ;
You are adding the Button to table row tableRow.addView(b);. I at first look at the code din't see it. Missed it.
So Make it final
final Button b = new Button(getApplicationContext());
// Use ActivtiyContext
final Button b = new Button(ActivityName.this);
// posted a link at the end read it.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
Inside onClick
public void onClick(View v) {
String value = b.getText().toString()
}
Also check
When to call activity context OR application context?
As per my way create String Array and :
String Title = new String[count];
And now implement like this:
for (int j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(j);
Title[a] = c.getString(c.getColumnIndex("jour");
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
Toast.makeText(getApplicationContext(), "Button click on(): "+Title[v1.getId()].toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is: "+v1.getId());
}
});
tableRow.addView(b);
c.moveToNext() ;
}
Try this code:
public void onClick(View v) {
String value = (Button)v.getText().toString()
}
First you give onclick event for Button like (buttonClick).
final Button testButton = new Button(getApplicationContext());
void buttonClick(View v){
Log.v("text", testButton.getText().toString()); // get the text
testButton.setText("sometext"); //to change the text
}
hi i am doing one application here i need to disply 6 images in 3 colunmns and 3 rows.and then when i click each image i need to perform different onclick action.i teried some way using arraylist with forloop.using below code i applied onclick function into all images but here 2 cloumn 3 images onclick function working but i first column 3 images not working onclick function.but i need to apply different onclick action to each button. so please any one help me how to apply onclick action to array of images.
game2 .class:
public class game2 extends Activity implements OnClickListener {
TableLayout layout;
int i=0;
int f=0;
Integer[] images={R.drawable.abig,R.drawable.cbig,R.drawable.dbig,R.drawable.abig,R.drawable.cbig,R.drawable.dbig};
List<Integer> solutionList = Arrays.asList(images);
Integer[] randomNumbers,randomNumbers1;
TableLayout.LayoutParams param,param1;
ImageView[] plus=new ImageView[6];
TableRow[] row = new TableRow[6];
RelativeLayout.LayoutParams lp2,lp1,lp3,lp4,lp5;
RelativeLayout linear;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
layout = new TableLayout (this);
layout.setLayoutParams( new TableLayout.LayoutParams(40,50) );
param=new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT);
param.setMargins(25, 0, 0, 0);
lp1=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
linear=(RelativeLayout)findViewById(R.id.linear);
Collections.shuffle(solutionList);
randomNumbers = (Integer[])solutionList.toArray();
int unique=0;
for (f=0; f<3; f++) {
row[f] = new TableRow(this);
for (int c=0; c<2; c++) {
plus[f]=new ImageView(this);
plus[f].setBackgroundResource(randomNumbers[unique]);
plus[f].setOnClickListener(this);
row[f].addView(plus[f], 200,100);
unique++;
} // for
layout.addView(row[f],param);
} // for
linear.addView(layout,lp1);
setContentView(linear);
}
public void onClick(View view) {
if(view==plus[0])
{
Toast.makeText(game2.this, "view", Toast.LENGTH_SHORT).show();
}
if(view==plus[1])
{
Toast.makeText(game2.this, "view1", Toast.LENGTH_SHORT).show();
}
if(view==plus[2])
{
Toast.makeText(game2.this, "view2", Toast.LENGTH_SHORT).show();
}
if(view==plus[3])
{
Toast.makeText(game2.this, "view3", Toast.LENGTH_SHORT).show();
}
if(view==plus[4])
{
Toast.makeText(game2.this, "view4", Toast.LENGTH_SHORT).show();
}
if(view==plus[5])
{
Toast.makeText(game2.this, "view5", Toast.LENGTH_SHORT).show();
}
}
}
Can this may be problem for (int c=0; c<2; c++)? use for (int c=0; c<3; c++) .. c<3 for 3 columns.. And let me know what happen..
EDIT:
Also
ImageView[] plus=new ImageView[9];
int unique=0;
for (f=0; f<3; f++) {
row[f] = new TableRow(this);
for (int c=0; c<3; c++) {
plus[unique]=new ImageView(this);
plus[unique].setBackgroundResource(randomNumbers[unique]);
plus[unique].setOnClickListener(this);
plus[unique].setId(unique);
row[f].addView(plus[unique], 200,100);
unique++;
}
And in onClick()
public void onClick(View view) {
switch(view.getId()){
case 0:
{
Toast.makeText(game2.this, "view", Toast.LENGTH_SHORT).show();
}
.
.
.
case 8:
{
Toast.makeText(game2.this, "view8", Toast.LENGTH_SHORT).show();
}
}
}
Use ArrayList instead of array.. Right now you are not adding all the elements.. In nested for loop your elemnts are getting replaced... So use ArrayList... And I don't see a need for such a complex code, You keep UI in XML and still can achieve the Same.. The present code is hard to understand and even you cannot after some days.. You cannot maintain this code..
Use plus[unique] in place of plus[f] in all 3 lines of below loop
for (int c=0; c<2; c++) {
... }
simple set ID to every imageView when creating ImageView. then setOnClickListener().
onClick(View v) {
switch(v.getId()) {
case 1st_ImageViewID:
break;
case 2nd_ImageView_ID:
break;
case 3rd_ImageView_ID:
break;
}
}
I wonder how I could navigate between the strings within an array, using the previous and next buttons, these strings will be displayed in a TextView. Thank you!
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f3);
setTitleFromActivityLabel (R.id.title_text);
TextView cumulos = (TextView) findViewById(R.id.cumulos);
TextView respostas = (TextView)findViewById(R.id.respostas);
Random randPhrase = new Random();
String[] cum = getResources().getStringArray(R.array.cumulos);
String[] resp = getResources().getStringArray(R.array.resp_cumulos);
String textout = "";
String textresp = "";
for (int i = 0; i < cum.length; i++) {
for (int j = 0; j < resp.length; j++) {
textresp = resp[j];
}
textout = cum[i];
}
cumulos.setText(textout);
respostas.setText(textresp);
}
Declare one int for index starting with 0 then in NextButton do
if(!index > resp.length-1 ) //not greater than array length
{
setText(resp[index++]);
}
else { nextButton.setEnabled(false); nextButton.setClicable(false); } //not clickable anymore
in PreviousButton do
if(!index < 0)
{
setText(resp[index--]);
}
else{
prevButton.setEnabled(false);
prevButton.setClicable(false);
}
Something like this? Mind this code is not tested, might throw exceptions.
It just to give you an idea.
You will need to create a next button and set an onClickListener for your button to navigate through the array. Lets say you also have a previous and next button. Try this:
Button btnNext = (Button) findViewById(R.id.yourNextbutton);
Button btnPrevious = (Button) findViewById(R.id.yourPreviousbutton);
int i = 0;
btnNext.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});
btnPrevious.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i>0){
i-=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});
I am doing an application in which I have to display the numbers on TextView randomly and automatically with the help of Timer. I am able to get the random Numbers in the log without repeating, but I am not able to print the same on device please help me...
Regards,
Akki
Source:
//RandomNumber.java
public class RandomNumber extends Activity{
static Random randGen = new Random();
int tambolanum,count=0;
private Button previousbutton;
private Button startbutton;
private Button nextbutton;
int bingonum[]=new int[90];
boolean fill;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.numbers);
LinearLayout number=(LinearLayout)findViewById(R.id.numbersview);
final TextView randomnum=(TextView)findViewById(R.id.numberstext);
previousbutton=(Button)findViewById(R.id.previous);
nextbutton=(Button)findViewById(R.id.next);
startbutton=(Button)findViewById(R.id.start);
startbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
//--- Initialize the array to the ints 0-90
do{
fill = true;
//Get new random number
tambolanum = randGen.nextInt(90) + 1;
//If the number exists in the array already, don't add it again
for(int i = 0; i < bingonum.length; i++)
{
if(bingonum == tambolanum)
{
fill = false;
}
}
//If the number didn't already exist, put it in the array and move
//To the next position
if(fill == true)
{
bingonum[count] = tambolanum;
count++;
}
} while(count < 90);
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
}
setText(CharSequence text)
The problem you're having is that you're overwriting your text in every itteration of this loop:
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
You need to build your string first then set it. Something like:
StringBuilder sb = new StringBuilder();
for(i=0;i /* where's the rest of this for-statement? */
{
sb.append(Integer.toString(bingonum[i]);
}
randomnum.setText(sb.toString());