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
}
Related
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;
}
}
}
i have added some button in a layout:
LinearLayout row = (LinearLayout)findViewById(R.id.KeysList);
keys=db.getKeys(console);
my_button=new Button[keys.size()];
for (bt=0;bt<keys.size();bt++){
my_button[bt]=new Button(this);
my_button[bt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
my_button[bt].setText(keys.get(bt));
my_button[bt].setId(bt);
row.addView(my_button[bt]);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[bt].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), keys.get(bt), 0).show();
}
}
});
}
I want to know which button is clicked and how to get text of the clicked button?And I think using bt here dose not seem to work!
This code is running. I hope it help you :)
final ArrayList<String> Keys = new ArrayList<String>();
for(int i = 0; i < 10; i ++){
Keys.add("Keys is : " + String.valueOf(i));
}
LinearLayout Row = (LinearLayout)findViewById(R.id.KeysList);
final Button[] my_button = new Button[Keys.size()];
for (int bt = 0; bt < Keys.size(); bt ++){
final int Index = bt;
my_button[Index] = new Button(this);
my_button[Index].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
my_button[Index].setText(Keys.get(Index));
my_button[Index].setId(Index);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[Index].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), Keys.get(Index), 0).show();
}
}
});
Row.addView(my_button[Index]);
}
ExampleProject id : Your project
You should probably use View#setTag to set some arbitrary data you'd like associate with the Button. Then you can just instantiate only one OnClickListener that then uses getTag and acts on that data in whatever way you need.
Another way is to have your Activity listen to all button clicks and then you just filter respective to the ID. You should not get the text of the button and use that at all. You should use your own type of identifier, ideally the idea should be enough. Or perhaps you use setTag as #qberticus described.
Consider This example :
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}
This works fine :)
Say I have buttons that are created dynamically:
for(int j = 0; j < spirits.length;
j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new SpiritsClickListener());
cabinet_layout.addView(imgBtn);
}
I want to change the text of the button every time it's pressed (On - Off)
How can I reference the buttons within the OnClickListener class?
in your onClickListener, you have a function called onClick(View v){} where v is the View that was clicked. You may use v to get details about the button, including its ID. You can also take this view, and if you know it is a button, cast it to a button.
Button clicked = (Button)v;
You can then use it in your javacode just as you would normally use a button.
Why don't you just call new OnClickListener() inside that loop like this
for(int j = 0; j < spirits.length;j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do what you need to do here
}
});
cabinet_layout.addView(imgBtn);
}
Create an OnClickListener for dynamically created buttons as:
// Create Listener for Button
private OnClickListener SpiritsClickListener = new OnClickListener()
{
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Button btn = (Button) view;
String btnText = btn.getText();
if(btnText.equalsIgnoreCase("On")){
btn.setText("Off");
}else{
btn.setText("On");
}
}
};
add this Listener to dynamically created buttons as:
imgBtn.setOnClickListener(SpiritsClickListener);
A table is being created such that:
TableLayout layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
layout.setPadding(1, 1, 1, 1);
for(int i=0; i<7; i++) {
TableRow tr = new TableRow(this);
for(int j=0; j<6; j++) {
Button b = new Button(this);
b.setText("0");
b.setOnClickListener(buttonListener);
tr.addView(b);
}
layout.addView(tr);
}
super.setContentView(layout);
The OnClickListener buttonListener is:
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View v) {
Button thisButton = (Button) findViewById(((Button)v).getId());
//thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
thisButton.getText();
}
};
The call to thisButton.getText() throws a NullPointerException, and I'm not sure why. Can anyone help me out?
TableLayout layout = new TableLayout(this);
layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
layout.setPadding(1, 1, 1, 1);
for(int i=0; i<7; i++) {
TableRow tr = new TableRow(this);
for(int j=0; j<6; j++) {
Button b = new Button(this);
b.setText("0");
b.setOnClickListener(buttonListener);
tr.addView(b);
}
layout.addView(tr);
}
setContentView(layout);
}
View.OnClickListener buttonListener = new View.OnClickListener() {
public void onClick(View v) {
Button btn1 = (Button)v;
//thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
String name = btn1.getText().toString();
}
};
I have tested this will work.
When you create view dynamically you don't to assgin an id to it.
you work using the object of the view.
I hope it makes sense to all the people who are curious to set id for dynamic buttons.
One problem in your code.
Have not set id of Button
b.setText("0");
b.setOnClickListener(buttonListener);
b.setId(i);
Assumption:
I can't see anything regarding setting id to button
The below line may causing exception:
Button thisButton = (Button) findViewById(((Button)v).getId());
Why are you doing? Instead you are already passing a view in click action: View v
So you can do straight way like:
String strText = ((Button) v).getText();
It mean your thisButton is probably null, because the statement before that was not successful.
Button thisButton = (Button) findViewById(((Button)v).getId());
does not look right. Usually the paramenter inside findViewById() should be a resource id.
such as
Button thisButton = (Button) findViewById(R.id.button);
R.id.button is defined by your layout xml.
You may simply get the text from the passed view, instead of recreating a button.
public void onClick(View v) {
if(v instanceof Button)
String text = ((Button) v).getText();
}
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]);
}
}
});