Multiple OnClickListeners Android - android

I have 10 buttons set up which are the answers to ten questions. When a certain button is clicked, I have a switch statement set up in my onClick method shown below. My question is what is the best way to set up the OnClickListeners for all the buttons seeing that I need to pass 2 arrays to the onClick method in order to tell if it is correct or not? Also, I need to return and integer value. Thanks
public void onClick(View v, int[] qaarray, int questionorder) {
int x=0;
switch(v.getId())
{
case R.id.imageButton0:
if(qaarray[0] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton1:
if(qaarray[1] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton2:
if(qaarray[2] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton3:
if(qaarray[3] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton4:
if(qaarray[4] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton5:
if(qaarray[5] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton6:
if(qaarray[6] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton7:
if(qaarray[7] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton8:
if(qaarray[8] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton9:
if(qaarray[9] == questionorder){
//correct
}else{
//incorrect
}
break;
default:
throw new RuntimeException("Unknown button ID");
}
}

The OnClickListener only gives you one parameter, which is the View:
void onClick(View v);
But you don't have to pass the questions and 'order' to the method to have what you want. One of the technique you can use is the setTag() method of View:
int[] button = new int[] { R.id.imageButton1, R.id.imageButton2.... };
private class AnswerPair{
public int questionOrder;
public int answer;
}
public void onCreate(Bundle bundle){
for(int i=0; i<NO_OF_BUTTON; i++){
AnswerPair ans = new AnswerPair();
ans.questionOrder = i;
ans.answer = 0; // SET this
getViewById(button[i]).setTag(ans);
getViewById(button[i]).setOnClickListener(this);
}
}
public void onClick(View v){
if (v.getTag() == null) return;
try{
AnswerPair answer = (ans)v.getTag();
// Check answer == question order? index?
}catch(exception e) return;
}

You can implement as many OnClickListeners as you want and assign different listeners for each button.
public void onCreate(Bundle bundle){
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.myButton)
b.setOnClickListener(new MyListener());
}
private class MyListener implements OnClickListener {
#Override
public void onClick(View v) {
// Your code here
}
}

i think a lot of people know this already, but there's a shortcut you can use instead of having different instances of onClickListeners and assigning them in code using setOnClickListener(x).
In your button XML, give it the android:onClick property, and assign it a string you like, for example,
android:onClick="clickOne"
In the activity the sets this xml as its content view, create a method named clickOne with a View parameter.
public void clickOne(View view)
Whatever you place on this method will be executed when you click the button.

Related

How to change several texts on button click in android studio

HELP ME PLEASE! I want to create 2 buttons ("Next" and "Previous") that will change the text in TextView. I made a switch and "systemcounter" to change the cases, which then will set another text in TextView. When I test my program in this window buttons do not change the pages. I think this is because the system cannot see the "systemcounter"
private Button next_button;
private Button previous_button;
private TextView Text_set1;
int systemcounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learningpage);
next_button = (Button) findViewById(R.id.next_button);
previous_button = (Button) findViewById(R.id.previous_button);
Text_set1 = (TextView) findViewById(R.id.Text_set);
next_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
systemcounter = systemcounter + 1;
}
});
previous_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
systemcounter = systemcounter - 1;
}
});
switch (systemcounter) {
case (0):
Text_set1.setText("Thermodynamics is the branch of physics that deals with the relationships between heat and other forms of energy.");
previous_button.setVisibility(View.INVISIBLE);
break;
case (1):
Text_set1.setText("Hi there");
previous_button.setVisibility(View.VISIBLE);
break;
case (2):
Text_set1.setText("How are you");
previous_button.setVisibility(View.VISIBLE);
break;
case (3):
Text_set1.setText("How old are you?");
break;
default:
Text_set1.setText("OPS");
break;
}```
you have switch statement in oncreate method and so it executes it only once, make a seperate method like
setEditText(int systemcount) and create your switch tehre and call this methods from button onclick methods
private void setText() {
switch (systemcounter) {
case (0):
Text_set1.setText("Thermodynamics is the branch of physics that deals with the relationships between heat and other forms of energy.");
previous_button.setVisibility(View.INVISIBLE);
break;
case (1):
Text_set1.setText("Hi there");
previous_button.setVisibility(View.VISIBLE);
break;
case (2):
Text_set1.setText("How are you");
previous_button.setVisibility(View.VISIBLE);
break;
case (3):
Text_set1.setText("How old are you?");
break;
default:
Text_set1.setText("OPS");
break;
}
}
and call this method in your listeners (like this)
next_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
systemcounter = systemcounter + 1;
setText();
}
});

How to add text to TextView without replacing the old text?

As I mentioned in the title ,I want to add text to a Textview without replacing the previous text .
In my application I have a TextView and 7 buttons .On every button click I set the text of button to the TextView.
If the button is clicked on first time ,Setting the text to TextView ,and if the same button is clicked 2nd time I am removing that button's text from TextView.
Here What I want to do is for 7 buttons I want to set positions(uniqueness for sun to sat) in TextView and when the respective button is clicked that text is set to the TextView and if the button is clicked 2nd time that specific position of the text should remove .
Here text shouldn't replace the previous text that is important to have and if some button's are selected and again that are deselected means TextView should show the default text as "Never"
I tried to get source from SO but I can't find a clear solution for this .
If anyone helps me to come out from this ,that's much helpful for me .
coding
public class CreateAlarm extends Activity implements View.OnClickListener {
private Button mbtn_Sun, mbtn_Mon, mbtn_Tue, mbtn_Wed, mbtn_Thu, mbtn_Fri, mbtn_Sat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
mRepeat = (TextView) findViewById(R.id.mRepeat);
mbtn_Sun = (Button) findViewById(R.id.mbtn_Sun);
mbtn_Mon = (Button) findViewById(R.id.mbtn_Mon);
mbtn_Tue = (Button) findViewById(R.id.mbtn_Tue);
mbtn_Wed = (Button) findViewById(R.id.mbtn_Wed);
mbtn_Thu = (Button) findViewById(R.id.mbtn_Thu);
mbtn_Fri = (Button) findViewById(R.id.mbtn_Fri);
mbtn_Sat = (Button) findViewById(R.id.mbtn_Sat);
mbtn_Sun.setOnClickListener((View.OnClickListener) this);
mbtn_Mon.setOnClickListener((View.OnClickListener) this);
mbtn_Tue.setOnClickListener((View.OnClickListener) this);
mbtn_Wed.setOnClickListener((View.OnClickListener) this);
mbtn_Thu.setOnClickListener((View.OnClickListener) this);
mbtn_Fri.setOnClickListener((View.OnClickListener) this);
mbtn_Sat.setOnClickListener((View.OnClickListener) this);
int hours = mTimePicker.getCurrentHour();
mCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mbtn_Sun:
if (mRepeat.getText().toString().contains("Sun")) {
mRepeat.setText("");
} else
mRepeat.setText("Sun");
break;
case R.id.mbtn_Mon:
if (mRepeat.getText().toString().contains("Mon")) {
mRepeat.setText("");
} else
mRepeat.setText("Mon");
break;
case R.id.mbtn_Tue:
if (mRepeat.getText().toString().contains("Tue")) {
mRepeat.setText("");
} else
mRepeat.setText("Tue");
break;
case R.id.mbtn_Wed:
if (mRepeat.getText().toString().contains("Wed")) {
mRepeat.setText("");
} else
mRepeat.setText("Wed");
break;
case R.id.mbtn_Thu:
if (mRepeat.getText().toString().contains("Thu")) {
mRepeat.setText("");
} else
mRepeat.setText("Thu");
break;
case R.id.mbtn_Fri:
if (mRepeat.getText().toString().contains("Fri")) {
mRepeat.setText("");
} else
mRepeat.setText("Fri");
break;
case R.id.mbtn_Sat:
if (mRepeat.getText().toString().contains("Sat")) {
mRepeat.setText("");
} else
mRepeat.setText("Sat");
break;
default:
mRepeat.setText("Never");
}
}
}
Image :
By default the TextView text is "Never".
You can define a TreeMap as:
private TreeMap<Integer, String> mAlarmDays = new TreeMap<>();
as a field of your class and add/remove the days to/from the TreeMap when the corresponding button is clicked. So the implementation of onClick method will be:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mbtn_Sun:
if (mRepeat.getText().toString().contains("Sun")) {
mAlarmDays.remove(0);
} else
mAlarmDays.put(0, "Sun");
break;
case R.id.mbtn_Mon:
if (mRepeat.getText().toString().contains("Mon")) {
mAlarmDays.remove(1);
} else
mAlarmDays.put(1, "Mon");
break;
case R.id.mbtn_Tue:
if (mRepeat.getText().toString().contains("Tue")) {
mAlarmDays.remove(2);
} else
mAlarmDays.put(2, "Tue");
break;
case R.id.mbtn_Wed:
if (mRepeat.getText().toString().contains("Wed")) {
mAlarmDays.remove(3);
} else
mAlarmDays.put(3, "Wed");
break;
case R.id.mbtn_Thu:
if (mRepeat.getText().toString().contains("Thu")) {
mAlarmDays.remove(4);
} else
mAlarmDays.put(4, "Thu");
break;
case R.id.mbtn_Fri:
if (mRepeat.getText().toString().contains("Fri")) {
mAlarmDays.remove(5);
} else
mAlarmDays.put(5, "Fri");
break;
case R.id.mbtn_Sat:
if (mRepeat.getText().toString().contains("Sat")) {
mAlarmDays.remove(6);
} else
mAlarmDays.put(6, "Sat");
break;
}
StringBuilder repeatDays = new StringBuilder();
if (mAlarmDays.size() == 0) {
repeatDays = new StringBuilder("Never");
} else {
for (String day:mAlarmDays.values()) {
repeatDays.append(day).append(" ");
}
}
mRepeat.setText(repeatDays.toString());
}
You should set each button id first,add this to your xml for each specific button : android:id="sun" and ...
My suggestion is: use a single TextView can make your logic quite complex
Use a horizontal LinearLayout instead, you will have 7 TextView inside with predefine text and position. Just simply show/hide them according to which button is clicked and you don't have to deal with any complex string analize.

android: how to set visibility on my textview with using arraylist value

I use arraylist to show/hide visibility of 3 textview, when i check array list for change visibility its work only one text view at same time, means if condition of 3 textview be true then 3 textview must be visible toghere, but its show me only one text view , how I can get it ? thank for ur help.
its my code :
public class Favorites_page extends Activity implements OnClickListener {
String on="on",off="off";
static TextView tv_fav1,tv_fav2,tv_fav3,tv_fav4,tv_fav5,tv_fav6,tv_fav7,tv_favoritetittle;
ArrayList<String> list = new ArrayList<String>(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
boolean check = list.isEmpty();
if(check){
list.add(0,off);list.add(1,off);list.add(2,off);
save();
}
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
int score = pref.getInt("score", 0);
//
tv_fav1= (TextView) findViewById(R.id.tv_fav1);
tv_fav2= (TextView) findViewById(R.id.tv_fav2);
tv_fav3= (TextView) findViewById(R.id.tv_fav3);
tv_fav4= (TextView) findViewById(R.id.tv_fav4);
tv_fav5= (TextView) findViewById(R.id.tv_fav5);
tv_fav6= (TextView) findViewById(R.id.tv_fav6);
tv_fav7= (TextView) findViewById(R.id.tv_fav7);
tv_favoritetittle=(TextView) findViewById(R.id.tv_favoritetittle);
tv_fav1.setOnClickListener(this);
tv_fav2.setOnClickListener(this);
tv_fav3.setOnClickListener(this);
tv_fav4.setOnClickListener(this);
tv_fav5.setOnClickListener(this);
tv_fav6.setOnClickListener(this);
tv_fav7.setOnClickListener(this);
switch (score) {
case 99:
if(score == 99){
tv_favoritetittle.setText("Nothing");
}
break;
case 100:
if(score == 100){
list.set(0,on);
save();
}
break;
case 101:
if(score == 101){
list.set(1,on);
save();
}
break;
case 102:
if(score == 102){
list.set(2,on);
save();
}
break;
default:
break;
}
//// the problem is here... with this command only textview is visible
if (list.get(0)==on) {
tv_fav7.setVisibility(View.VISIBLE);
}else {
tv_fav7.setVisibility(View.GONE);
}
if (list.get(1)==on) {
tv_fav6.setVisibility(View.VISIBLE);
}else {
tv_fav6.setVisibility(View.GONE);
}
if (list.get(2)==on) {
tv_fav5.setVisibility(View.VISIBLE);
}else {
tv_fav5.setVisibility(View.GONE);
}
} // marbot be Content
public void save()
{
Bundle value= new Bundle();
value.putStringArrayList("temp1", list);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
} // marbot be Activity
also i add this code to my cods , but its not work too
for (int i = 0; i < list.size(); i++) {
switch (i) {
case 0:
if(list.get(0)==on){
tv_fav7.setVisibility(View.VISIBLE) ;
}
case 1:
if(list.get(1)==on){
tv_fav6.setVisibility(View.VISIBLE) ;
}
case 2:
if(list.get(2)==on){
tv_fav5.setVisibility(View.VISIBLE) ;
}
default:
break;
}
}
I believe your problem is, why only one TextView is Visible and why not others?
It's because you are getting only one value from sharedPreferences & saving it in score variable and when it goes to switch(), it goes to only one case if that is true.
Suppose if you are getting score 100 from sharedPrefences,
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
int score = pref.getInt("score", 0); // now score value is 100
then it goes to switch() block and will do the operation only in this part
case 100:
if(score == 100){
list.set(0,on);
save();
}
So, when it comes down to check this if condition,
if (list.get(0)==on) {
tv_fav7.setVisibility(View.VISIBLE);
}
this returns true & tvfav7 visibility will be Visible.
But, when it goes to next if condition block,
if (list.get(1)==on) {
tv_fav6.setVisibility(View.VISIBLE);
}else {
tv_fav6.setVisibility(View.GONE);
}
this will fail because in switch block, it doesn't go to the below case to set second position and third position to on.
case 101:
if(score == 101){
list.set(1,on);
save();
}
break;
case 102:
if(score == 102){
list.set(2,on);
save();
}
break;
as the score is not 101 or 102. It's 100. So, just remember in switch block, only one case will be executed if it's true and not entire thing.

Android better way to do button clicks?

So right now I'm tidying up some code, and I have a lot of else/ifs for buttons and was wondering what is a good way to do it and make it neater?
So I have like 12 buttons, and each button plays a sound and changes colour when clicked. I have a method for this but I was wondering is there a good way to just detect the button instead of if/else?
public void onClick(View v) {
int id = v.getId();
changeToWhite();
if (id == R.id.a_button) {
currentButton(a, 81);
} else if (id == R.id.aSharp_button) {
currentButton(aSharp, 82);
} else if (id == R.id.b_button) {
currentButton(b, 83);
} else if (id == R.id.c_button) {
currentButton(c, 72);
}
Etc...
So is there a better way of having this? I know having a lot of else/ifs is bad so I wanted to try improve it.
Thanks!!
You can use "switch-case" instead.
>
public void onClick(View v) {
switch(v.getId())
{
case R.id.a_button:
changeToWhite();
break;
case R.id.aSharp_button:
currentButton(aSharp,82);
break;
.....
default:
break;
}
}
How about using a case statement instead?
public void onClick(View v) {
// Perform action on click
switch(v.getId()) {
case R.id.a_button:
currentButton(a, 81);
break;
case R.id.aSharp_button:
currentButton(aSharp, 82);
break;
/*
and the rest of the cases here.
*/
}
}
I assume you're using XML and setting the onClick property.
An easier/tidier way is to use anonymous inner classes.
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foo);
findViewById(R.id.view_buttonone).setOnClickListener(new OnClickListener(){
public void onClick(View view){
// button one clicked
}
});
findViewById(R.id.view_buttontwo).setOnClickListener(new OnClickListener(){
public void onClick(View view){
// button two clicked
}
});
}
First of all there is virtually no penalty for using if/else nesting. There's no need to try this level of micromanaging your app. You will gain no benefits from it. Try to think more of optimizing this point in terms of readability.
Now, to answer your question, you could use a switch/case construct instead.
public void onClick(View v) {
switch (item.getItemId()) {
case R.id.aBar_item1:
//Item onClick logic
return true;
case R.id.aBar_item2:
//Item onClick logic
return true;
case R.id.aBar_item3:
//Item onClick logic
return true;
...
}
}

Check RadioGroup checked or not and get value to static int

GOAL 1: When click the button, if there isn't any radiobutton checked, it will warning user by Toast; if a radiobutton checked, it will take user to new activity (or do smt up on you).
First
public class hanh1_2 extends Activity{
public static int ButID;
#Override
Second, set the button action:
final Button ok2 = (Button) findViewById(R.id.ok2);
ok2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Set int of ButID = checkedradiobuttonID
//If ButID = -1 --> there isn't bt checked
int ButID = tieng.getCheckedRadioButtonId();
if (ButID == -1){
Toast.makeText(hanh1_2.this, "Check a butt pls", Toast.LENGTH_SHORT).show();
}
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
startActivity(intent2);
}
}
});
Meaningless to advanced, but may helpful for some newbie like me :)
Have a look at the Form stuff tutorial on the Android dev site. You can supply an OnClickListener to all RadioButtons and keep track of the one selected (if any).
private OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
};
Alternatively, you can potentially use the RadioGroup's getCheckedRadioButtonId() method.
As illustrated in one of the other answers: pass the int value as an extra to the Intent you use to launch your second Activity:
// In first activity
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putInt("selected_index", selectedIndex);
startActivity(i);
// In second activity
int selectedIndex = getIntent().getExtras().getInt("selected_index");
Take all your RadioButton and RadioGroup to class level.
initialize them inside onCreate()
now inside onClick() get id of checked RadioButton and compare like this:
public void onClick(View v) {
int checked = tieng.getCheckedRadioButtonId(); // tieng is your RadioGroup
switch(checked)
{
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "First is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Second is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Third is selected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(hanh1_2.this, "pleas check any button", Toast.LENGTH_SHORT).show();
break;
}
}
put extra along with intent :
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
intent2.putInt(Index1, index1);
startActivity(intent2);
}
now inside second activity onCreate() read this extra :
{
int Index1 = getIntent().getExtras().getInt("Index1");
//do stuff here
}

Categories

Resources