how to make a button do multiple things? - android

I have a question regarding android development. I am trying to make an app that changes the screen color from red to blue and then green. I have asigned an onClickListener to a relativeLayout, that turns the screen from white to red. How do I make that same onClickListener do multiple things in an order, so that when I click the screen once it turns it to red and when I click it again it will turn the screen to blue etc.
Here is my code so far:
final RelativeLayout layout = (RelativeLayout) findViewById(R.id.view);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layout.setBackgroundColor(Color.parseColor("#ff0000"));
}
});

Store the list of desired colors in an array. Keep track of the current color index and increment after each click like so:
final RelativeLayout layout = (RelativeLayout) findViewById(R.id.view);
layout.setOnClickListener(new View.OnClickListener() {
String[] colors = new String[]{"#ff0000", "#00ff00", "#0000ff"};
int colorIndex = 0;
#Override
public void onClick(View view) {
String color = colors[colorIndex];
colorIndex = colorIndex++ % colors.length;
layout.setBackgroundColor(Color.parseColor(color));
}
});
The modulo operator (%) ensures we don't index past the end of the array.

track the state of your click. Like this
private int colorState =0;
final RelativeLayout layout = (RelativeLayout) findViewById(R.id.view);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(colorState){
case 0:
layout.setBackgroundColor(Color.parseColor("#ff0000"));
break;
case 1:
layout.setBackgroundColor(Color.parseColor("#000000"));
break;
case 2:
layout.setBackgroundColor(Color.parseColor("#FFFFFF"));
break;
colorState++;
}

Related

How to retrieve string value of text view and again set calculated double to that text view in android?

my project contains the grid view in which i created the custom view. Custom view had minus button, text view and plus button. My intention is like that, when i press on minus or plus button, the value of text view get changes according to some point. Please tell me how to implement that.
Thanks in advance.
String number = mTextView.getText()
int numberInt = Integer.parseInt(number);
IN plus button onClickListener
numberInt++
IN minus button onClickListener
numberInt--
and final
mTextView.setText(""+numberInt);
TextView mCount = (TextView) findViewById(R.id.count);
Button plus = (Button) findViewById(R.id.plus);
Button minus = (Button) findViewById(R.id.minus);
plus.setOnClickListener(onClickListener);
minus.setOnClickListener(onClickListener);
private final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.minus:
mCount.setText(String.valueOf(Double.valueOf(mCount.getText().toString()) - 1));
return;
case R.id.plus:
mCount.setText(String.valueOf(Double.valueOf(mCount.getText().toString()) + 1));
return;
default:
}
}
};
You can set OnClickListener on button inside your gridView adapter, like this:
button.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = mTextView.getText().toString();
double number = Double.parseDouble( data );
number++; //if you want to increase it by 1
//or
number += someValue; //if you want to increase it by some value
mTextView.settext(String.valueOf( number ));
}
} );
similarly you can set click listener on another button to subtract the value, just replce
number++;
//or
number += someValue;
with
number--;
//or
number -= someValue;

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

how to detect that tablerow has been pressed

i know that i can use this for each tablerow but it's very long code
setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//perform action
}
});
but i have 12 table row i think that this is very long.. maybe with this structure
tablelayout {
if (tablerow.id = 1) {
// action if i pressed the first row
} else if (tablerow.id = 2) {
// action if i pressed the second row
}
}
You can call setOnItemClickListener directly on your ListView. So, instead of calling setOnClickListener in your adapter's getView method, just use this:
ListView mListView = (ListView) findViewById(R.id.listview);//or whatever the id is
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//then use a switch statement
switch(position) {
case 1 :
//do something if first row is clicked
break;
case 2 :
//row 2 clicked
break;//don't forget these breaks
}
}
});
You could use View.setTag(Object obj):
OnClickListener mListener = new OnClickListener() {
public void onClick(View v) {
Integer tag = (Integer)v.getTag();
switch (tag.intValue()) {
case ROW1: ...
}
}
});
and the time you fill your rows just do (maybe in a loop over all row-ids):
TableRow row = tableLayout.findViewById(ROW1);
row.setTag(ROW1);
row.setOnClickListener(mListener);
By the way, the Tag can also be set in XML...
If you are using a TableLayout, you can add the individual OnClickListener to the elements that are inside of your TableRow (which is inside of your TableLayout).
For example if you have a Button and a TextView inside of a TableRow and you want your button to do something when clicked, then you should add the OnClickListener to the button. If all of the buttons go to the same place, but send different data depending on the position in the TableLayout then you can do something like this:
String[] texts; //The different texts your button could say
for(int i = 0; i < 12; i++){
final Button yourButton = new Button(this);
yourButton.setText(texts[i]);
yourButton.setOnClickListener(new OnClickListener(){
Intent i = new Intent(this, YourClass.class);
i.putExtra(yourButton.getText());
startActivity(i);
}
}
If your TableRow only contains one element, you should be using a ListView instead of a TableLayout as Phil suggested.
I hope that kind of gives you an idea on a direction you can go, but it really depends on what you need to do with the item that is being clicked on.
/************ if table row is dynamic then this method else method 2 is perfect************/
//if we want to applay listener on dynamic tablerow then use this
//sure that perfect
TablRowe tr = new TableRow(this);
tr.setClickable(true);
tr.setId(100);// if in loop then add 1 counter with 100 like (100+counter) at end count++ it
tr.setOnClickListener(this);
#Override
public void onClick(View v)
{
switch (v.getId())
{
case 100:
Toast.makeText(getApplicationContext(), "100", Toast.LENGTH_SHORT).show();
break;
case 101:
Toast.makeText(getApplicationContext(), "101", Toast.LENGTH_SHORT).show();
break;
}
/************************** for simple like this ************************/
TableRow row1 = (TableRow)findViewById(R.id.row1);
row1.setonClickListener(this);
public void onClick(View v)
{
switch (v.getId())
{
case R.id.row1:
// do work
break;
}
}

Checking a Button exists in Android

Need some advice again.
I am 99% done with this module I'm working on, although I'm stuck at the last hurdle. I'm dynamically publishing a button on the screen at runtime. This button will take it to a new activity view when pressed. I got that working perfectly.
However, I have another button which randomly changes the view so it effectively needs to reset itself, if that makes sense. What's happening is each time the button is clicked (the dynamic one) it then adds another button to the stack. Effectively I have buttons each time I click running down the screen. Is my logic wrong or is there a way to check and prevent the button to show each time? i.e. Just once...Below is the code.
public void ButtonOnClick(View v) {
Random rnd = new Random();
int randomListIndex = rnd.nextInt(2);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(Page1.this, R.anim.fadein);
int firstRun = 0;
switch (randomListIndex) {
case 0:
//get the image your going to muck with
image = (ImageView) findViewById(R.id.cardImageView);
//set the image with what it should be
image.setImageResource(R.drawable.storm);
//apply the transition effect so it looks correct
image.startAnimation(myFadeInAnimation);
button = (Button)findViewById(R.id.dynamicButton);
button.setText("Need another question?");
Button myButton = new Button(this);
myButton.setText("Press Me");
LinearLayout layout = (LinearLayout) findViewById(R.id.nextPageContainer);
layout.addView(myButton);
final Button myButton1 = myButton;
myButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String activityName = "Storm";
Intent intent = new Intent(Page1.this, Page2.class);
intent.putExtra(ACTIVITYNAME,activityName);
startActivity(intent);
}
});
break;
}
}
EDIT: How about this? Add a new class field member (a class variable, not a method's local variable) that indicates whether the button was actually added in the layout.
private boolean buttonShown = false; /* Here changed */
public void ButtonOnClick(View v) {
Random rnd = new Random();
int randomListIndex = rnd.nextInt(2);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(Page1.this, R.anim.fadein);
int firstRun = 0;
switch (randomListIndex) {
case 0:
//get the image your going to muck with
image = (ImageView) findViewById(R.id.cardImageView);
//set the image with what it should be
image.setImageResource(R.drawable.storm);
//apply the transition effect so it looks correct
image.startAnimation(myFadeInAnimation);
button = (Button)findViewById(R.id.dynamicButton);
button.setText("Need another question?");
if (buttonShown == false) { /* Here changed */
Button myButton = new Button(this);
myButton.setText("Press Me");
LinearLayout layout = (LinearLayout) findViewById(R.id.nextPageContainer);
layout.addView(myButton);
final Button myButton1 = myButton;
myButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String activityName = "Storm";
Intent intent = new Intent(Page1.this, Page2.class);
intent.putExtra(ACTIVITYNAME,activityName);
startActivity(intent);
}
});
buttonShown = true; /* Here changed */
} /* Here changed */
break;
}
}
Edited again: Instead of local variable myButton, I used class field member pressMeButton.
private Button pressMeButton;
public void ButtonOnClick(View v) {
Random rnd = new Random();
int randomListIndex = rnd.nextInt(2);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(Page1.this, R.anim.fadein);
int firstRun = 0;
switch (randomListIndex) {
case 0:
//get the image your going to muck with
image = (ImageView) findViewById(R.id.cardImageView);
//set the image with what it should be
image.setImageResource(R.drawable.storm);
//apply the transition effect so it looks correct
image.startAnimation(myFadeInAnimation);
button = (Button)findViewById(R.id.dynamicButton);
button.setText("Need another question?");
if (pressMeButton == null) {
pressMeButton = new Button(this);
pressMeButton.setText("Press Me");
LinearLayout layout = (LinearLayout) findViewById(R.id.nextPageContainer);
layout.addView(pressMeButton);
}
/* If the pressMeButton is already in the layout, all you need to do is just changing the onClickListener. */
pressMeButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
String activityName = "Storm";
Intent intent = new Intent(Page1.this, Page2.class);
intent.putExtra(ACTIVITYNAME,activityName);
startActivity(intent);
}
});
break;
}
}
Your code is fine but the way it is it will always add a button to the screen. Whats the desired behavior your looking for? If its a conditional thing than you need to account for that in the onclick call.
EDIT:
So what you need to do then is to create some kind of flag or id for the button and set it as the button's view.tag like this:
Button b = new Button(context);
b.setTag(flagTag);
Then when you want to check if the button exists you check it like:
if((LinearLayout) findViewById(R.id.nextPageContainer))
.findViewById(tagFlag)==null){
Button b = new Button(context);
b.setTag(flagTag);
}else{
//do nothing or something :p
}

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

Categories

Resources