Dynamic Buttons and OnClickListener - android

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

Related

Changing the Color of the Dynamically loaded Buttons onclick

Android: I have created dynamic buttons based on my arraylist size,Lets consider 10 buttons. When a button is clicked, the color of the button will change to grey. When another one is clicked, the color of the previous button should be reset to the default color.
boolean iscolor = true;
final LinearLayout linearLayout = view.findViewById(R.id.total_count);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
for (int j =1;j<=datalist.size()/2;j++) {
final Button btn = new Button(getContext());
final int id_ = j;
btn.setText("" + j);
btn.setTextColor(Color.WHITE);
btn.setMaxWidth(5);
btn.setId(id_);
btn.setPadding(8, 8, 8, 8);
btn.setBackgroundColor(getContext().getResources().getColor(R.color.DarkBlue));
linearLayout.addView(btn, params);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!iscolor ) {
btn.setBackgroundColor(getResources().getColor(R.color.DarkBlue));
iscolor =true;
}
else
{
btn.setBackgroundColor(getResources().getColor(R.color.gray));
iscolor = false;
}
}});
How to restore the color of the previous clicked Button in Android.
Try this :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* you need to have already stored buttons in a data structure, something like : List<Button> btns; */
for(Button b : btns){
if(b.getId() == v.getId(){ b.setBackgroundColor(getResources().getColor(R.color.gray)); } else{ b.setBackgroundColor(getResources().getColor(R.color.yourdefaultcolor)); } //no need for isColor variable
}});
linearLayout.addView(btn, params);

setText on TextViews created using a for loop - android

I have created a set of TextViews programmatically using a for loop. This what i have tried.
for(int i=1; i<5; i++){
valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel"+x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP,22);
valueTV.setTextColor(Color.parseColor("#333333"));
i++;
}
this.valueTV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
valueTV.setText("Hello");
}
});
I need to change the text of clicked TextView to "Hello". How can i achieve this?
You have to add a listener to all your TextView created.
And be careful, you incremented i twice : one in the first line of the for and another one in the end of the for.
for (int i = 1; i < 5; i++)
{
final TextView valueTV = new TextView(AddMyVehicle.this);
linearLayout.addView(valueTV);
vehicleModelReturned = myVehicleData.getString("VehicleModel" + x, "");
valueTV.setText(vehicleModelReturned);
valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
valueTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
valueTV.setTextColor(Color.parseColor("#333333"));
valueTV.setId("test");
valueTV.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
TextView tv = (TextView) v;
tv.setText("Hello");
}
});
}
First, set the OnClickListener to all the TextViews you create, not just the last one. That is, move the setOnClickListener() inside the for loop.
Second, in onClick(), change the text of the clicked view and not again the last one you created. The View v param is the view that was clicked. You can cast it to TextView.

Android OnClickListener throws NullPointerException

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

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