I have a button with the "btnadd" id ,
Button add = (Button) findViewById(R.id.btnadd);
And a function with two inputs ,
public void CheckNumber (int i , int j) { if (i != j) Toast.makeText(getBaseContext,"i is not equal to j"); }
And I want to set this function for the click event of this button
add.setOnClickListener(CheckNumber(2,4));
This code is not correct, but how can I do this?
You need to define a new View.OnClickListener inside of setOnClickListener.
Try this:
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkNumber(2, 4);
}
});
Complete Solution:
Try something like this:
First, Create a method: (Consider your case)
public void CheckNumber (int i , int j) {
if (i != j)
Toast.makeText(this, "i is not equal to j", Toast.LENGTH_SHORT);
}
Second, declare the button inside onCreate():
Button add = findViewById(R.id.btnadd);
Then finally, add a click listener:
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckNumber(2, 4);
}
});
That's it. Hope it helps.
Related
So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far.
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
//do something
}
}
});
}
Any tips on how to solve this?
Take final String[] x={"defaultvalue Emptry"}
Then after inside onclick Listener set value of x using below code.
x[0]="new value"
and use this value in different function.
as per your code it look likes blow:
final String x[] ={""}
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
x[0]=checkBoxes_fiber[i].getvalue==> value name
}
}
});
}
Outside function get value of x using
String name=x[0]
You can try to create separate class of listener
private View.OnClickListener mCheckboxListener = new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)view).isChecked())
{
int checkBoxId = (int)v.getTag(); //You can get Id for specific checkbox
//do other stuff with checkBoxId
}
}
};
And set Id to each checkbox like
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes.setTag(i); //set check box id as tag for later usage
checkBoxes_fiber[i].setOnClickListener(mCheckboxListener);
}
I guess you are trying to do something base on the checkbox IDs. You can set a tag for a checkBox and get back the tag in future. Also, the view object in method void onClick(View view) is now an CheckBox. Just change a little in your code:
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setTag(i); //mark the check box id for later usage
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(((CheckBox)view).isChecked()){
int checkBoxId = (int)view.getTag();
doSomething(checkBoxId);
}
}
});
}
}
And write a new method for business code:
public void doSomething(int no){
if(no==1){
//do something
}
else if(no==2){
//do something
}
//...
}
Hi I'm working at my first bigger app in android studio "FlashCards". I would like it to work so after you click on the button the flashcard's textview changes its text to next random flashcard untill you see all of the them how can i do something like 'continue' to my loop from inside onClick method.
here's the loop's code:
while(i < mTestDeck.size()) {
// generates random number which will represent position in deck.
int random = randomGenerator.nextInt() % mTestDeck.size();
// if random flashcard was already shown create random number again
if (mTestDeck.get(random).wasShown())
continue;
//text view that we will operate on
TextView deckTextView = (TextView) findViewById(R.id.flashcard_text_view);
// set text
deckTextView.setText(mTestDeck.get(random).getFront());
// set mWasShown to true
mTestDeck.get(random).flashcardShown();
Button myButton = (Button) findViewById(R.id.know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTestDeck.correctAnswer();
}
});
myButton = (Button) findViewById(R.id.dont_know_answer);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, this way, you have a potential infinite loop. And if it can happens, it will happens! It's not a good idea to "get random item and check if it's ok or try again".
I think that it's better to keep a list with all items in a random order. You just have to iterate over it.
Something like:
int currentPosition = 0;
List<Card> items = new ArrayList<Card>(mTestDeck).shuffle();
// Call this method once in onCreate or anywhere you initialize the UI
private void function setCurrentCard() {
Card currentItem = items.get(currentPosition);
[...] // Set all UI views here
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentPosition > items.size) {
// TODO? End?
return;
}
currentPosition++;
setCurrentCard();
}
});
}
I have 2 activies. In first code, you see 2 rows and their click listeners. When first row clicked, I want to send "0" index to 2nd activity. As same, when I clicked second row, I want to send "1". So like that.
How can I do that?
Sender Side:
TableRow tricepsRow1;
tricepsRow1=(TableRow) findViewById(R.id.arm_exercise_1);
tricepsRow1.setClickable(true);
tricepsRow1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
indexValueStandart=0;
Intent tricepsRowIntent = new Intent(getApplicationContext(),exercise_arm_triceps.class);
tricepsRowIntent.putExtra("extra_arm_triceps",indexValueStandart);
startActivity(tricepsRowIntent);
}
});
TableRow tricepsRow2;
tricepsRow2=(TableRow) findViewById(R.id.arm_exercise_2);
tricepsRow2.setClickable(true);
tricepsRow2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
indexValueStandart=1;
Intent tricepsRowIntent = new Intent(getApplicationContext(),exercise_arm_triceps.class);
tricepsRowIntent.putExtra("extra_arm_triceps2",indexValueStandart);
startActivity(tricepsRowIntent);
}
});
Receiver Side:
int getVIndexValue= getIntent().getIntExtra("extra_arm_triceps",0);
deneme.setText(String.valueOf(getVIndexValue));
try this:
int value = getIntent().getExtras().getInt("extra_arm_triceps");
I'm new to Java (coming from Python) and I'm trying to pass a method as a parameter in order to convert this code:
Button button1;
Button button2;
...
Button buttonN;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button1(v);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button2(v);
}
});
(...)
buttonN = (...)
To something like:
public AssignListener( integer tButton, Method tMethod )
{
button_view = (Button) findViewById(tButton);
button_view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
tMethod(view);
}
}
}
(...)
AssignListener( R.id.button1, onClick_button1 );
AssignListener( R.id.button2, onClick_button2 );
(...)
AssignListener( R.id.buttonN, onClick_buttonN );
I've read that you can't pass methods to functions, and some advice to wrap my function using Runnable to achieve this.
I have not clear idea about how to do it. Any idea on how do it easily? :?
Thanks.
EDIT: Should I wrap "AssignListener" in its own class and pass the class itself? :?
You can call findViewById() and seOnClickListener into onCreate method, and OnClickListenet outside the onCreate.
Button button1 = (Button)findViewById(R.id.button1);
or
findViewById(R.id.button1).seOnClickListener(mClickListener);
findViewById(R.id.button2).seOnClickListener(mClickListener);
findViewById(R.id.button3).seOnClickListener(mClickListener);
findViewById(R.id.button4).seOnClickListener(mClickListener);
private OnClickListener mClickListener = new View.OnClickListener(
public void onClick(View view){
switch(view.getId()){
case R.id.button1:
//button1 click handle here...
break;
case R.id.button2:
//button2 click handle here...
break;
case R.id.button3:
//button3 click handle here...
break;
case R.id.button4:
//button4 click handle here...
break;
}
});
Try it, hope it will helpful to you.
You could define and pass an onClickListener like this:
public AssignListener( integer tButton, OnClickListener listener ){
tButton.setOnClickListener(listener);
}
The simplest way is to create listener implementation for each button, as is written in your first snippet.
I don't see any reasonable benefit of having universal method like AssignListener(). Don't reinvent bicycle, use existing setOnClickListener() method and pass listener specific for button.
An easy solution would be to create a function called tMethod that takes a button id, and has a switch statement that allows for a certain action to be performed for the given button id. This would then be called inside the onClick function like tMethod(view.getId()).
Btw, Python has methods. Java has functions. Pedant mode turned off!
public class MyClass implements OnClickListener, OnLongClickListener {
Button button1;
Button button2;
...
Button buttonN;
. . .
setButtonsListener(findViewById(<your top view id>));
. . .
void setButtonsListener(ViewGroup vg) {
int count = vg.getChildCount();
Button btn;
View v;
for(int i=0; i < count ; i++) {
v = vg.getChildAt(i);
if( v instanceof Button ) {
btn = (Button)v;
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
} else if( v instanceof ViewGroup ) {
setButtonsListener((ViewGroup) v);
}
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
I am creating a small 'Click Counter' app, which basically has a button function, which when pressed, a textview field displays the number of clicks made.
I am trying to setup a 'Reset' button, which changes the value of the textview back to 0. This is the code I have so far:
wreset = (Button)findViewById(R.id.wreset);
wreset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
txtCount.setText(String.valueOf(0));
}
This changes the textview value to 0, however when the button is clicked again it starts back from the count which it was on when the reset button was clicked.
For example:
a. the current count = 10
b. reset button is selected
c. current count = 0
d. clicker button pressed
e. current count = 11
Am I using the wrong statement or intent?
Your not resetting whatever counter you are using:
#Override
public void onClick(View arg0) {
yourCounter = 0;
txtCount.setText("0");
}
You need to save the counter state in an instance field or a static field. Then set that field to zero on reset. For example:
private int counter = 0;
// ...
wreset = (Button) findViewById(R.id.wreset);
wreset.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
counter = 0;
txtCount.setText(String.valueOf(counter));
}
}
increment = (Button) findViewById(R.id.increment);
increment.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
counter++;
txtCount.setText(String.valueOf(counter));
}
}
public void onClick(View view) {
int count = 0;
count++;//increment the count
TextView text = (TextView) findViewById(R.id.counttxt);// resorce location
text.setText("No.of Clicks " + count);// view in the text