Can anyone help me? I'm stuck on this thing for about week. I want to set one button to do several things. For example: when I pressed button once - b1.setBackgroundResource(R.drawable.a), when I pressed twice - b1.setBackgroundResource(R.drawable.b), when pressed third - b1.setBackgroundResource(R.drawable.c) and so on. It is possible to do this? Very thanks!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
}
}
);
}
Have an int counter defined. In the onClick increment it and do whatever you want based on it's value
Yes it is possible
use button property known as setTag and getTag. It work same as that of flag
Example:
b1.setTag("1");
b1.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
if b1.getTag().equals("1"){
b1.setTag("2")
}
else if(b1.getTag().equals("2")) {}
}
}
);
I found a recent tutorial, detailing and explaining how to do what you want but it is accomplished using a short and long button press.
Try this: https://www.youtube.com/watch?v=cUgL8b7M8ns
Hope it helps.
Create a global variable
private int index = 0;
Then in your code do this
b1.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
switch (index) {
case 0:
firstFunction();
break;
case 1:
secondFunction();
break;
}
// Advance your counter and extract the %
index++;
index = index % numOfDifferentFunctions;
}
}
);
Related
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1;
final ImageView image;
button1 = (Button) findViewById(R.id.button1);
image = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int j=0;
while(j<=4){
int res=getResources().getIdentifier("d002_p00"+j,"drawable",getPackageName());
image.setBackgroundResource(res);
j = j+1;
}
}
});
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
}
}
I have 3 questions:
What is wrong with this code this code only show 1st and last image? how I can fix it?
I don't want to rotate my apps. How I can do that?
How I can mentioned a user in Stack Vverflow? I tried #username but it didn't work.
Answer for question 1: What is wrong with this code this code only show 1st and last image? how I can fix it?
Put the int j outside the onClick and change the while to an if
int j=0;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(j >= 0 && j <= 4){
int res = getResources().getIdentifier("d002_p00"+j, "drawable", getPackageName());
image.setBackgroundResource(res);
j++;
}
}
});
Answer for question 2: I don't want to rotate my apps. How I can do that?
See this answer of another stackoverflow question.
Answer for question 3: How I can mentioned a user in Stack Vverflow? I tried #username but it didn't work.
I don't know for sure myself, but I think you can't use #user_name to reply a comment when there is only one commenter apart from yourself (at least I couldn't). If you want to credit someone however, I would suggest putting their profile-page in a link like so: #user3546792 (Click their name, copy the link, click the Add Hyperlink-button in SO and paste the copied link. Then change [enter link description here] to [#user_name]
For question 2:
I don't want to rotate my apps. How I can do that?
Your just add this in your android Manifest:
android:orientation="portrait"
I have been looking at some posts and still I cannot get mine code to work (I am a beginner) .. I am just tring to use the toast with my two buttons with a case switch .. When compiling it just crashes .. one something has an idea ?
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
TextView et = (TextView) findViewById(R.id.txtHeader);
Button btnAdd = (Button) findViewById(R.id.btnAdd);
Button btnDis = (Button) findViewById(R.id.btnDisplay);
btnAdd.setOnClickListener((OnClickListener) this);
btnDis.setOnClickListener((OnClickListener) this);
}
public void OnClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
// Toast msg = Toast.makeText(getBaseContext(), "Torben", Toast.LENGTH_LONG);
// msg.show();
break;
case R.id.btnDisplay:
// Toast msg1 = Toast.makeText(getBaseContext(), "Henriksen", Toast.LENGTH_LONG);
// msg1.show();
break;
default:
break;
}
}
I see two main problems:
((OnClickListener) this
Make sure your class implements OnClickListener because you never need to cast if you are actually implementing the interface.'
The declaration of the class should be something like:
public class MyActivity extends Activity implements OnClickListener
Then change OnClick to lowercase o.
#Override
public void onClick(View v) {
some log output would be helpful!
a wild guess is that your activiy does not implement OnClickListener, why else would you cast this to OnClickListener?
just check in your layout manifest that whether the buttons id are correct and given the same id which your are using and if it is then please update the question with the LogCat output.
And also check that the activity is defined in manifest because there is no mistake in your code to implemts the onclick listener for multiple buttons.
Enjoy!!
Example adding a button listener:
Button b = ((Button)findViewById(R.id.button_name));
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//do something
}
});
and make sure the button is defined in your xml file with the id #+id/button_name or #id/button_name (just make sure they match)
I am trying to change the background image of a button that is clicked. The button whose image I am trying to toggle is the same button that is clicked. I ultimately want the program to test the current background image and change it to the other picture given the result of the test.
final Button testButton = (Button) findViewById(R.id.buttonTestButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//toggle picture
if (testButton.equals(getResources().getDrawable(R.drawable.fakepicture))) {
testButton.setBackgroundResource(R.drawable.alternatepicture);
}
else {
testButton.setBackgroundResource(R.drawable.fakpicture);
}
}//end void onClick
});//end test button on click listener
try
testButton.getBackground().equals(getResources().getDrawable(R.drawable.fakepicture));
However ToggleButton might suit your case better.
As others have said, your equals method is comparing the button itself with the image, but you need to compare the background drawables.
I recommend loading the images drawables you want to use and then using their references later to make things more clear, something like this:
final Drawable first = getResources().getDrawable(
android.R.drawable.arrow_up_float);
final Drawable second = getResources().getDrawable(
android.R.drawable.arrow_down_float);
final Button testButton = (Button) findViewById(R.id.toggleButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (testButton.getBackground().equals(first)) {
testButton.setBackgroundDrawable(second);
} else {
testButton.setBackgroundDrawable(first);
}
}
});
as the other friends answered , it is preferable to use the ToggleButton in Android ,
and in your case, if you want to keep your code , so your method should be like this :
final Button testButton = (Button) findViewById(R.id.buttonTestButton);
int status = 0;//GLOBAL VARIABLE : the status of the Button ( 0 or 1 )
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//toggle picture
if (status == 0) {
testButton.setBackgroundResource(R.drawable.alternatepicture);
status=1 ; // change the status to 1 so the at the second clic , the else will be executed
}
else {
testButton.setBackgroundResource(R.drawable.fakpicture);
status =0;//change the status to 0 so the at the second clic , the if will be executed
}
}//end void onClick
});//end test button on click listener
You can simply use ToggleButton: Android ToggleButton and use StateList for the changing of the background: StateList using the check attribute.
You can use Buttons or Image buttons..
private ImageButton mod1,mod2;
mod1 = (ImageButton) findViewById(R.id.mod1);
mod2 = (ImageButton) findViewById(R.id.mod2);
mod1.setOnClickListener(this);
mod2.setOnClickListener(this);
public void onClick(View v) {
mod1.getDrawable().clearColorFilter();
mod2.getDrawable().clearColorFilter();
switch (v.getId()) {
case R.id.mod1:
mod1.getDrawable().setColorFilter(0xfff47521,PorterDuff.Mode.SRC_ATOP);
break;
case R.id.mod2:
mod2.getDrawable().setColorFilter(0xfff47521,PorterDuff.Mode.SRC_ATOP);
break;
}
}
I'm having a button in a sliding drawer in a Android Application. The problem is it does not seem to react to any clicks as normal buttons do.
I'm guessing the problem is that it's a different view than buttons on the normal view.
If I implement a button the normal way like this
myAgenda = (Button)findViewById(R.id.BtnMyAgenda);
myAgenda.setOnClickListener(this);
public void onClick(View v) {
switch(v.getId()){
case R.id.BtnMyAgenda:
test.setAnimation(leftLeft);
test.startAnimation(leftLeft);
break;
}
I'm guessing there is something wrong with the above code since the button is in a SlidingDrawer and not in the "normal" view.
Any ideas how to fix the problem?
Here is the code
Register with event listner like below code
button.setOnClickListener(clickButtonListener);
and create this listner for button
private OnClickListener clickButtonListener= new OnClickListener()
{
#Override
public void onClick(View v)
{
if(v == button)
{
}
}
}
I actually found the solution to the problem, I simply created a new view.onclicklistener specific to that button.
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.
#Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..
Update: code could be soemthing along these lines:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
as a method in the activity and then use it in the loop like this
button.setOnClickListener(getOnClickDoSomething(button));
I got one solution for this..
use this code in onCreate
linear = (LinearLayout) findViewById(R.id.linear);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
btn[i] = new Button(getApplicationContext());
btn[i].setText(num_array_name[i].toString());
btn[i].setTextColor(Color.parseColor("#000000"));
btn[i].setTextSize(20);
btn[i].setHeight(100);
btn[i].setLayoutParams(param);
btn[i].setPadding(15, 5, 15, 5);
linear.addView(btn[i]);
btn[i].setOnClickListener(handleOnClick(btn[i]));
}
after onCreate create one method of return type View.OnClickListener like this..
View.OnClickListener handleOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
}
};
}
Button.OnClickListener btnclick = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button)v;
Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();
}
};
call this listener by btn.setOnClickListener(btnclick);
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.
Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().
instead use setTag() function to distinct easily.
for(int i=0;i<4;i++) {
Button btn = new Button(this);
btn.setTag(i);
btn.setOnClickListener(new View.OnclickListener() {
#Override
public void onClick(View v) {
int i=v.getTag();
switch(i) {
case 1: btn.setText(i);
break;
case 2: btn.setText(i);
break;
case 3: btn.setText(i);
break;
case 4: btn.setText(i);
break;
default: btn.setText("Others");
}
}
}
"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.
I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.
Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout
This answer may you help:
https://stackoverflow.com/a/5291891/2804001
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");
}
}