get OnClick() from programmatically added buttons? - android

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 :)

Related

One Toggle Button on at a time

I am working on a an Android Application . i have created some toggle buttons dynamically and they are clickable too...
what i want to achieve is toggle on any specific button and its ok.
but when i toggle on any other button all other toggle button should go off..
like i can toggle on any one button at a time . if any other pressed on the previous one should go off.
there are dynamic number of buttons ..
and i dont know how to achieve this .
here is my code :
for ( int i = 0; i<sez; i++ ){
final ToggleButton btn = new ToggleButton(xxxxx.this);
String g = contactList.get(i).toString();
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(g);
while (m.find()) {
String[] po=m.group(1).split("=");
btn.setId(i);
btn.setTextOn("play");
btn.setText(po[1]);
btn.setTextOff(po[1]);
final int id_ = btn.getId();
Rowlayout layout = (org.xxxx.xxx.ui.Rowlayout) findViewById(R.id.adios);
layout.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(InCallScreen.this,
list2.get(id_) + "", Toast.LENGTH_SHORT).show();
}
});
}
}
i have spent 3 days on it but still stuck in it, any one can help me . it will be much appreciated....
This code works perfectly for me. However I have removed a lot of your code to simplify the answer. So in trust you can modify those values I have set since I don't know the value of sez or the rowlayout I have replaced their values as sez = 10 and the layout to a linear layout.
Anyways here is the code.
public class MainActivity extends Activity
{
int sez;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sez = 10;
for ( int i = 0; i<sez; i++ ){
final ToggleButton btn = new ToggleButton(MainActivity.this);
btn.setId(i);
btn.setTextOn("play");
btn.setText("click");
btn.setTextOff("off");
final int id_ = btn.getId();
LinearLayout layout = (LinearLayout) findViewById(R.id.mainLinearLayout);
layout.addView(btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
int buttonId = btn.getId();
for(int ii = 0; ii<sez; ii++)
{
if(ii!=buttonId)
{
ToggleButton ButtonToOff = (ToggleButton)findViewById(ii);
ButtonToOff.setChecked(false);
}
}
}
});
}
}
}
The part you probably have to add to your code is mainly in the onClick() method.
Hope in helped! :)

Use a button to add other buttons, editText etc.

I need to be able to add buttons to a layout using an "add" button. The problem is that I need each button to have an OnClickListener()/onClick method. I was thinking every time the "add" button is pressed then i would add a new button to an array but im not sure add the listener and implement an onClick method for each button I create.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SmartChronometer chrono = (SmartChronometer) findViewById(R.id.chrono);
final Button start = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (chrono.isRunning())
chrono.pause();
else {
chrono.chronoStart();
}
}
});
}
I need to add chronomoter,button and listeners every time I click an "Add" button.
set all the clicklisteners as you wich!
call findViewById(R.id.btnSecond).setVisibility(View.GONE); on creat, then when clickin the first button
Button btnSecond;
...
public void onClick(View v) {
findViewById(R.id.btnSecond).setVisibility(View.VISIBLE);
if (btnSecond.getVisibility() == View.VISIBLE); {
findViewById(R.id.btnThird).setVisibility(View.VISIBLE);}
}
this way you can put all your information in the java file and all buttons in xml, but they will be hidden until click.
This is one way, other answer my come. Good Luck :)
implements OnClickListener
Button add = (Button) findViewById (R.id.addButton);
add.setOnClickListener (this);
List<Button> buttons = new ArrayList <Button>();
for (int i = 0; i < buttons.size (); i++){
buttons.get (i).setOnClickListener (this);
}
#Override
public void onClick (View v){
for (int i = 0; i < buttons.size (); i++){
if (v.getId () == buttons.get (i).getId ()){
// do stuff you want
}else if (v.getId() == R.id.addButton){
//add button
}
}
}
Hope this will work, didnt test it.

Android change text color of button programmatically

I am creating button dynamically in linearlayout horizontalscrollview and on click i get selected button position.
I want to know how to change text color of selected button?
Here is my code.
String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT", "SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"};
private LinearLayout ll;
Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);
for(int i = 0; i < categories.length; i++) {
btn = new Button(this);
btn.setText(categories[i]);
btn.setBackgroundColor(Color.parseColor("#ffffff"));
btn.setOnClickListener(buttonClick);
ll.addView(btn);
int idx = ll.indexOfChild(btn);
btn.setTag(Integer.toString(idx));
// btn.setId(idx);
}
}
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
//(String)v.getTag();
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};
check the type and assign the text color
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
if(v instanceof Button){
((Button)v).setTextColor(Color.parseColor("#000000"));
}
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};
try this
Edited Answer
((Button)view).setTextColor(Color.parseColor("#000000"));
please check the following answer here and here .
as you can see you can do it programmatically and through xml by creating a style file for all of the states of the button .
Hope that helps
This works:
button.setTextColor(getColor(R.color.blue))
I just check all already posted solutions. No one works.
They also produce error like this
btnjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setTextColor(int)' on a null object reference
Real Solution :
Step-1: When you try to change setTextColor then always use try/catch, to prevent app from Crash.
Step-2: No matter you define your Button already, define(like R.id.btnId) again before setTextColor code line.
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.btnId);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use try/catch for handle any kind of error
try {
Button btnForTextColorChange= (Button) findViewById(R.id.btnId);
// must define Button again before setTexColor code line
btnForTextColorChange.setTextColor(getResources().getColor(R.color.white));
} catch (Exception e){
Log.e(TAG, "Error:"+e);
}
}
});
}
[sorry for bad english]
Happy Coding :)
This worked for me:
btnItem.setTextColor(ContextCompat.getColor(context, R.color.black))

How to check which ImageButton was prssed?

I have lots of image buttons. User can press any of those button and i need to know which button is pressed. These buttons appears dynamically so i don't know how much of them will be.
For one image button i would write this listener:
ImageButton ib = new ImageButton(this);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
}
});
But how to do one listener for all my Images Buttons? Can i recognize which button was pressed by it's tag ? Like tag would be ID from sqlite.
Also i put image to button with this code:
button.setImageDrawable( testPic );
button is ImageButton and testPict is drawable (image)
But when i press this button it don't show that it is pressed if i do this:
button.setBackgroundColor(R.color.transparent_background);
I had to do this because i just want to see Buuton image which i could press and recognize what i pressed.
Thanks.
ok what you can do is that you can write a single callback function and then set it to each and every button it will allow you to handle each button with a sing function like :
View.OnClickListener btn_listener = View.OnClickListener() {
#Override
public void onClick(View v) {
// Do whatever work you want.
int id = v.getid();
// check for id and do you task.
}
Arraylist<Button> btn_group = new Arraylist<Button>;
or
Arraylist<int> btn_id_group = new ArrayList<int>;
for (int i =0; i < 10; i++) {
Button btn = new Button(getApplicationContext());
btn.setId(i);
btn_id_group.add(i) or btn_group.add(btn);
btn.SetOnClickListener(btn_listener);
}
I think it will work for you.
You can use View.setTag(object) and View.getTag() and store in it sqlite id. Something like this:
View.OnClickListener listener = View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TravelBite.this, (String)v.getTag(), Toast.LENGTH_SHORT).show();
//or some function that do somthing useful
//if( ((String)v.getTag).equals("image1") ){} or anything else
}
And in for loop:
String tagFromSqlite = "image1";
ImageButton ib = new ImageButton(this);
ImageButton.setTag(tagFromSqlite);
ib.setOnClickListener(listener);
final OnClickLisener listener = new OnClickListener() {
public void onClick(View v){
switch((Integer)v.getTag()){
case R.id.zero:
break;
case R.id.one:
break;
case R.id.two:
break;
}
}
}
//when init the Buttom
ImageButton btn = new ImageButton(Context);
btn.setTag(NUMBER);
you'll have to manually assign ID's to keep them separated - I had to do something similar (1000 was the base ID I chose to add upon as well)
Although View v in the listener refers to the button pressed, when you programmatically create buttons the id's are not unique and caused me issues, so that's why I set them specifically
View.OnClickListener btn_listener = View.OnClickListener()
{
#Override
public void onClick(View v)
{
//you can use v.getID() here
}
}
for (int i =0; i < 10; i++)
{
Button btn = new Button(getApplicationContext());
btn.setID( 1000 + i );
btn.SetOnClickListener(btn_listener);
}

setOnClick for 100 buttons

I have 100 buttons (from button000 to button 999). Is there any way to setOnClick for all of them? Because all button have the same function.
Thanks in advance.
If your buttons are inside a layout then do like this.
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
View v = ll.getChildAt(i);
v.setOnCLickListener(this);
}
Buddy try this way
import android.view.View.OnClickListener;
public class MyActivity extends Activity implements OnClickListener {
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonA = (Button) findViewById(R.id.buttonA);
buttonA.setOnClickListener(this);
Button buttonB = (Button) findViewById(R.id.buttonB);
buttonB.setOnClickListener(this);
}
//etc... etc...
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
// do something
break;
case R.id.buttonB:
// do something else
break;
}
}
At right now I can say easiest way in
use button000.setOnclicklistener(this);
:
:
button999.setOnclicklistener(this);
and implement Onclicklistener in this current class....
if you are sure that it's the best way for your app to create 1000 buttons, then it will be something like this:
Button [] my_button=new Button[1000];
LinearLayout ll=(LinearLayout)findViewById(R.id.mylayout);
for (int i=0;i<1000;i++){
my_button[i]=new Button(this);
my_button[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
my_button[i].setText("button "+i);
ll.addView(my_button[i]);
my_button[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
////click event
}
});
}
Just add your buttons in an array and
Just loop the buttons and on a listener you can call the following block of code:
for (int i=0; i < buttonArray.length; ++i){
buttonArray[i].onClick(this);
}
there are two methods one is you can set onClick in xml layout file by onClick method you can define the method, that should be invoked when button is clicked. This method is appropriate when you define buttons in xml.
If you are adding buttons in Activity, and if you are adding in a loop then you can do as
for(int i=0; i<100; i++)
{
//Create and Add button
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
//Operations
}
});
}
Best way to make Button Dynamically like
Integer[] button_Ids = {R.id.btn000,R.id.btn001...............,R.id.btn999};
for(int i=0;i<100;i++)
{
Button btn = (Button)findViewById(button_ids[i]);
btn.setOnClickListner(this);
}
#Override
public void onClick(View v)
{
Toast.make(getApplicationContext,"Hello",1000).show();
}
If all buttons have exactly same functionality then you can simple use
private OnClickListener mListenr=new OnClickListener(
#Override
public void onClick(View v) {
//Whatever you want
}
for(int i=0; i<100; i++)
{
mButton[i].setOnClickListener(mListenr);
}
you can refer this to see ways to implement listener.

Categories

Resources