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.
Related
This is the first time I'm ever dabbling in Android development so please bear with me.
My requirement is this:
I have two buttons on screen, A and B. If the user presses both buttons (order doesn't matter), I need another page to be displayed. Pressing either A or B should do nothing.
Is this possible? If so, how would I achieve this?
Thank you.
This is possible if you take a flag. (boolean)
You should set a flag in your button listeners.
public class Mtest extends Activity {
Button b1;
Button b2;
boolean flag_1 = false;
boolean flag_2 = false;
public void onCreate(Bundle savedInstanceState) {
...
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(myhandler1);
b2.setOnClickListener(myhandler2);
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
flag_1 = true;
doSomething();
}
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 2nd button
flag_2 = true;
doSomething();
}
};
}
public void doSomething(){
if(flag_1 && flag_2)
{
//DO SOMETHING
}
}
}
Create two boolean's like button1isClickedand button2isClicked,then set an onClickListener for each Button. When the the Button is clicked set the value of these two boolean's to true, then simply create an if() statement that will chekc to see if both buttons have been clicked, like this:
if(button1isClicked == true && button2isClicked == true){
//display your new page
}
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 :)
Can any one tell me? how can i use the same button for two Action?
Like em using one button in my activity that calculate some values and after calculating the when i again press same button then reset the all fields. Like in this Application
http://www.craziness.com/games/play-love-tester/ when i test the love by pressing the button
then i again press the same button then all fields reset.
what should i use in my activity for the above problem?
You can create a global variable which indicates the state of the program and then change this value when needed. In the OnClickListener of your Button you create an if statement which checks this variable and does the needed things for the associated value.
Example:
public class MainActivity extends Activity {
private int state = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (state == 0) {
// State 1
}
else if (state == 1) {
// State 2
}
else {
// Default state
}
}
});
// Rest of your code including state changing part
}
}
You can do it by changing the button text.
If you do not want that someone sees the text change. Test (example "click" and the other state "click " (1 blank at the end) or another solution.
....
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// todo: check for expected instance (Button)
Button btc = (Button)v;
String bText = btc.getText().toString();
if (bText == "open") {
btc.setText("close");
}
else if (bText == "close") {
btc.setText("open");
}
}
[...]
You can do so by using a toggle button.
In your xml file add a toggle button
<ToggleButton
android:id="#+id/tbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textOff="Reset"
android:textOn="Calculation"
android:background="#drawable/icon"/>
Java file
public class Reviews extends Activity implements OnClickListener {
private ToggleButton tbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tbtn = (ToggleButton) findViewById(R.id.tbtn);
tbtn.setOnClickListener(this);
public void onClick(View view) {
if (tbtn.isChecked()) {
//calculate the result
}
else {
//Reset your global calculation variable;
}
}
}
}
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);
}
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.