Android Button: Shorten OnClick method - java

Is it possible to have multiple buttons calling the same method? I mean the parameters would be the ID of the button. My problem is that I got a really, really long switch case function and every case has the same methods. Here is my code snippet (I have shortened it):
public class HerkunftRind extends Activity implements View.OnClickListener, Animator.AnimatorListener {
private static final String TAG = "HerkunftRind";
ViewFlipper viewFlipper;
ImageButton myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.herkunft_rind);
viewFlipper = (ViewFlipper) findViewById(R.id.herkunft_rinder_view_flipper);
ImageButton imageButton = null;
imageButton = (ImageButton) findViewById(R.id.button_1);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.button_2);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.button_3);
imageButton.setOnClickListener(this);
imageButton = (ImageButton) findViewById(R.id.button_4);
imageButton.setOnClickListener(this);
}
public void setAnimationFade(int id) {
myButton = (ImageButton) findViewById(id);
ObjectAnimator animator = ObjectAnimator.ofFloat(myButton, View.ALPHA, 0.5f, 1f);
animator.setDuration(300); //ms
animator.start();
animator.addListener(this);
}
#Override
public void onAnimationStart(Animator animation) {
myButton.setAlpha(1f);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_1: {
setAnimationFade(R.id.button_1);
text = (TextView) findViewById(R.id.button_1_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_1_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.button_2: {
setAnimationFade(R.id.button_2);
text = (TextView) findViewById(R.id.button_2_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_2_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.button_3: {
setAnimationFade(R.id.button_3);
text = (TextView) findViewById(R.id.button_3_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_3_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.button_4: {
setAnimationFade(R.id.button_4);
text = (TextView) findViewById(R.id.button_4_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_4_text_2);
text.setVisibility(View.VISIBLE);
break;
}
What I don't want is to define it directly in the XML file. Can I make this shorter?

Yes, you can, I personally do that very often.
You can call the method in the xml layout.
i.e.:
<Button
android:onClick="myMethod()"
/>
Mind that myMethod() must have a signature like
public void myMethod(View v)
Inside myMethod you may then want to discern which is the View you clicked (which can also be heterogeneous) and act consequentially.
Just add a switch() where you use v.getId() to determine which is the View which fired the event.
Something like this:
switch(v.getId())
{
case R.id.txtPhone:
{
// Do something
// ...
break;
}
case R.id.txtMenu:
{
// Show options menu
// ...
break;
}
// ...
default:
{
break;
}
}

this here is a little bit redundant:
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_1: {
setAnimationFade(R.id.button_1);
text = (TextView) findViewById(R.id.button_1_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_1_text_2);
text.setVisibility(View.VISIBLE);
break;
}
case R.id.herkunft_rinder_bauer2_button: {
setAnimationFade(R.id.button_2);
text = (TextView) findViewById(R.id.button_2_text_1);
text.setVisibility(View.VISIBLE);
text = (TextView) findViewById(R.id.button_2_text_2);
text.setVisibility(View.VISIBLE);
break;
}
...
why you just dont call setAnimationFade before the hole switch case..??
public void onClick(View v) {
setAnimationFade(v.getId());
switch (v.getId()) {
case R.id.button_1: {
setAnimationFade(R.id.button_1

If you don't want a long onClick method, then you could write an onClick listener to each button.
E.g:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
anotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});

Related

Whe button continueButton isnt working? It should start the new Activity if I have a text in EditText or make a Toast

I work with a program which should make parameters for character. A person writes a name then generate force and health by clicking the button. After all, he click the continueButton which should start the MainActivity if name exists or make a Toast text. But it's not working. The problem should be in the end of onClick method.
There is a code
public class CreateActivity extends AppCompatActivity
implements View.OnClickListener {
final Random random = new Random();
String toastText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
}
#Override
public void onClick(View v) {
Button continueButton = findViewById(R.id.continueButton);
Button getData = findViewById(R.id.getData);
final EditText newName = findViewById(R.id.newName);
TextView newHealth = findViewById(R.id.newHealth);
TextView newForce = findViewById(R.id.newForce);
continueButton.setOnClickListener(this);
getData.setOnClickListener(this);
newName.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()== KeyEvent.ACTION_DOWN &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
Character.name = newName.getText().toString();
return true;
}
return false;
}
});
switch (v.getId()){
case R.id.getData: {
Character.health = random.nextInt(100);
newHealth.setText(String.valueOf(Character.health));
Character.force = random.nextInt(100);
newForce.setText(String.valueOf(Character.force));
}
// THERE IS A PROBLEM
if (newName.getText().toString().equals("")) {
switch (v.getId()) {
case R.id.continueButton:
startActivity(new Intent(this, MainActivity.class));
finish();
return;
}
} else{
switch (v.getId()) {
case R.id.continueButton:
Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
}
Initialize your Button inside onCreate method. Like this:
public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
private Button yourButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourButton= findViewById(R.id.your_button_id);
yourButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
switch (view.getId()) {
case R.id.your_button_id:
// Do something
}
}
}

Java Android: the button does not work after returning to the first layout

when I press two buttons the picture changes but when I move with the 3 button to the 2nd layout and I go back to the first picture it doesn't change anymore
public class MainActivity extends AppCompatActivity {
private Button button1;
private Button button2;
private Button changeLayout;
private Button exit;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
imageView = findViewById(R.id.imageView);
changeLayout = findViewById(R.id.changeLayoutBt);
exit = findViewById(R.id.exitBtn);
}
public void changeImage(View view) {
switch (view.getId()){
case R.id.button1:
imageView.setImageResource(R.drawable.orange);
break;
case R.id.button2:
imageView.setImageResource(R.drawable.java);
break;
}
}
public void changeLayout(View view) {
setContentView(R.layout.second_layout);
}
public void exit(View view) {
setContentView(R.layout.activity_main);
}
}
`
In order to create new layout got to File>New>Activity>Empty Activity
Change your changeLayout code to this one
public void changeLayout() {
startActivity(new Intent(MainActivity.this, Main2Activity.class);
}
Main2Activity.class is your newly created java class. It would be Main2Activity.java or what ever you named it.
Inside your onCreate() method. Just below
changeLayout = findViewById(R.id.changeLayoutBt);
Paste this code
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeLayout();
}
});

How to update image in fragment when selecting an image in an Activity?

Hello I'm trying to select an Image in an activity page and that selected image to update in my Fragment page. I've tried what I've learnt previously, but it's not working at all. Below is what I've attempted. I'm still new to android development, so please bear with me.
ProfileSettingsActivity.java:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
profileImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
profileImage6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
});
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Below is the Fragment that contains the page I start on from and go to the ProfileSettingsActivity page
PeopleFragment.java:
public class PeopleFragment extends Fragment {
ImageButton settingsButton;
PieChart pieChart;
ImageButton profileImage;
private FirebaseAuth mAuth;
TextView fullName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_people2, container,
false);
profileImage = (ImageButton) view.findViewById(R.id.imageButton4);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
getActivity().startActivityForResult(settingsClick,0);
}
});
fullName = (TextView) view.findViewById(R.id.userProfileFullName);
mAuth = FirebaseAuth.getInstance();
return view;
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
/**
* Updates the view according to the authentication status.
* #param user the current FirebaseUser
*/
private void updateUI(FirebaseUser user) {
if (user != null) {
fullName.setText(user.getDisplayName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) return;
//Getting the Avatar Image we show to our users
ImageView avatarImage =
(ImageView)getView().findViewById(R.id.imageButton4);
//Figuring out the correct image
String drawableName = "profile1";
switch (data.getIntExtra("imageID",R.id.teamid00)) {
case R.id.teamid00:
drawableName = "profile1";
break;
case R.id.teamid01:
drawableName = "profile2";
break;
case R.id.teamid02:
drawableName = "profile3";
break;
case R.id.teamid03:
drawableName = "profile4";
break;
case R.id.teamid04:
drawableName = "profile5";
break;
case R.id.teamid05:
drawableName = "profile6";
break;
default:
drawableName = "profile1";
break;
}
int resID = getResources().getIdentifier(drawableName, "drawable",
getActivity().getPackageName());
avatarImage.setImageResource(resID);
}
}
Currently with what I have above, I can move from the fragment page to the activity page and I can press on the buttons to select the images and then the activity closes for me. But when I'm back on the fragment page, the profile image isn't updated at all, and displays the default one.
Try to use startActivityForResult() instead of getActivity().startActivityForResult(). So, change your Fragment code to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent settingsClick = new Intent(getActivity(),
ProfileSettingsActivity.class);
startActivityForResult(settingsClick,0);
}
});
...
return view;
}
Note: This is not related to your problem.
You can simplify you activity code to this:
public class ProfileSettingsActivity extends AppCompatActivity {
ImageView profileImage1;
ImageView profileImage2;
ImageView profileImage3;
ImageView profileImage4;
ImageView profileImage5;
ImageView profileImage6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_settings);
profileImage1 = (ImageView) findViewById(R.id.teamid00);
profileImage2 = (ImageView) findViewById(R.id.teamid01);
profileImage3 = (ImageView) findViewById(R.id.teamid02);
profileImage4 = (ImageView) findViewById(R.id.teamid03);
profileImage5 = (ImageView) findViewById(R.id.teamid04);
profileImage6 = (ImageView) findViewById(R.id.teamid05);
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
setProfilePicture(view);
}
};
profileImage1.setOnClickListener(clickListener);
profileImage2.setOnClickListener(clickListener);
profileImage3.setOnClickListener(clickListener);
profileImage4.setOnClickListener(clickListener);
profileImage5.setOnClickListener(clickListener);
profileImage6.setOnClickListener(clickListener);
}
public void setProfilePicture(View view) {
//Creating a Return intent to pass to the Main Activity
Intent returnIntent = new Intent();
//Figuring out which image was clicked
ImageView selectedImage = (ImageView) view;
//Adding stuff to the return intent
returnIntent.putExtra("imageID", selectedImage.getId());
setResult(RESULT_OK, returnIntent);
//Finishing Activity and return to main screen!
finish();
}
}
Probably you've got some problems with your onActivityResult method. Check these answers.
Also there is a solution that is going to work:
1. Tag your fragments when you create them:
FragmentTransaction fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.main_layout, new PeopleFragment(), "PeopleFragmentTag"));
fTrans.commit();
2. Write method in PeopleFragment, which could setImage:
public void updateProfileImage(int profileImgID){
/* Update your image here */
}
3. Get a fragment by tag and call the method:
public void setProfilePicture(View view) {
/* Your code */
PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentByTag("PeopleFragmentTag");
peopleFragment.updateProfileImage(selectedImage.getId());
}
Hope, I helped you somehow. Good luck!

radiobuttons (change condition to onclick)

In general have this screen:
How to put conditions from OnClick to onCheckedChanged (radiobutton). It works only with one variable price_53_off in OnClick, but I want when checked other radiobutton (500 gr.) program parses other variable (price_73_off) and calculate other cycle.
Some code below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ImageView plus;
ImageView minus;
TextView tvResult;
TextView price;
TextView price_53_off;
TextView price_73_off;
RadioGroup radioGroup_price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
plus = (ImageView) findViewById(R.id.plus);
plus.setOnClickListener(this);
minus= (ImageView) findViewById(R.id.minus);
minus.setOnClickListener(this);
tvResult = (TextView) findViewById(R.id.tvResult);
price = (TextView) findViewById(R.id.price);
price_53_off = (TextView) findViewById(R.id.price_53_off);
price_73_off = (TextView) findViewById(R.id.price_73_off);
radioGroup_price = (RadioGroup) findViewById(R.id.radioGroup_price);
radioGroup_price.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioButton_250:
price.setText("53");
break;
case R.id.radioButton_500:
price.setText("73");
break;
}
}
});
}
#Override
public void onClick(View v) {
int parse_quant;
int parse_price_53;
int num2 = 1;
int result = 0;
int resultprice=0;
parse_quant = Integer.parseInt(tvResult.getText().toString());
parse_price_53 = Integer.parseInt(price_53_off.getText().toString());
switch (v.getId()) {
case R.id.plus:
result = parse_quant + num2;
resultcena= result*parse_price_53;
}
switch (v.getId()) {
case R.id.minus:
result = parse_quant - num2;
if (parse_quant==1){
return;
}
resultprice= result*parse_price_53;
}
tvResult.setText( String.valueOf(result) );
price.setText( String.valueOf(resultprice) );
}
}
In order for result and resultPrice variables to be available in both onCheckChanged and onClick, you need to store them at the class level instead of local inside the onClick method.

Android:How to set listener on multiple image buttons?

First of all, I'm using Andorid and Java only for a week and I'm a total newbie.
I need to know which button user clicked and then compare it with good or bad answer.
Here is the code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
Integer[] flags = {
R.drawable.flag_albania,
R.drawable.flag_andorra,
R.drawable.flag_angola,
R.drawable.flag_avganistan,
};
String[] questions = {
"What is the flag of Albania",
"What is the flag of Andorra",
"What is the flag of Angola",
"What is the flag of Avganistan",
};
TextView tv = (TextView) findViewById(R.id.textView1);
int arraySize = flags.length;
Random rand = new Random();
ImageButton button1 = (ImageButton) findViewById(R.id.imageButton1);
int index = rand.nextInt(arraySize);
int questionIndex1 = index;
button1.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button2 = (ImageButton) findViewById(R.id.imageButton2);
index = rand.nextInt(arraySize);
int questionIndex2 = index;
button2.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button3 = (ImageButton) findViewById(R.id.imageButton3);
index = rand.nextInt(arraySize);
int questionIndex3 = index;
button3.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button4 = (ImageButton) findViewById(R.id.imageButton4);
index = rand.nextInt(arraySize);
int questionIndex4 = index;
button4.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
Integer[] question = {
questionIndex1,
questionIndex2,
questionIndex3,
questionIndex4
};
int questionArraySize = question.length;
int questionArray = rand.nextInt(questionArraySize);
tv.setText(questions[question[questionArray]]);
My idea is to compare questionIndex that is randomly selected to a button id but I really don't know how to implement it. Every help is appreciated.
Use this reduced code
ImageButton button1,button2,button3,button4;
ImageButton imagebuttons[]={ button1,button2,button3,button4};
int ids[]={R.id.imageButton1,R.id.imageButton2,R.id.imageButton3,R.id.imageButton4};
for(final int i=0;i<imagebuttons.length;i++)
{
imagebuttons[i]=(ImageButton) findViewById(ids[i]);
int index=rand.nextInt(arraySize);
imagebuttons[i].setImageResource(flags[index]);
flags[index] = flags[--arraySize];
indexes.put(i,index);
imagebuttons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( questionArray==indexes.get(i))
{
}
}
});
I hope this will help you
Try out this way:
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
/**
* Common click listener
*/
OnClickListener onClickListener = new OnClickListener()
{
#Override
public void onClick(View p_v)
{
switch (p_v.getId())
{
case R.id.imageButton1:
//Your logic here.
break;
case R.id.imageButton2:
//Your logic here.
break;
}
}
}
Write below code
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
/// Your Above Code ///
tv.setText(questions[question[questionArray]]);
Imagebutton1.setOnClickListener(this);
Imagebutton2.setOnClickListener(this);
Imagebutton3.setOnClickListener(this);
Imagebutton4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == Imagebutton1){
// Write Your Code Here
} else if(v == Imagebutton2){
// Write Your Code Here
} else if(v == Imagebutton3){
// Write Your Code Here
} else if(v == Imagebutton4){
// Write Your Code Here
}
}
}
You can do it this way:
First, make your activity implements onClick Listener:
public class MyActivity extends Activity implements View.OnClickListener{
Then set the action listeners to your buttons:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
.....
then in the listener, check the id:
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
break;
case R.id.imageButton2:
break;
....
}
}
You can do the it this way also. You have to use some int variables to keep the tag value of the button. And also you have to create a onClickListner for the button actions. Coding is as follow
public class MyActivity extends Activity{
//Define the Tag values for image buttons.
private static final int TAG_IMAGE_BTN_1 = 0;
private static final int TAG_IMAGE_BTN_2 = 1;
private static final int TAG_IMAGE_BTN_3 = 2;
private static final int TAG_IMAGE_BTN_4 = 3;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initActivity();
}
private void initActivity(){
//Initialize the image buttons via xml or from the code itself.
//Add the onClickListner_BTN_CLICK and the corresponding tag to the image button
imageBtn1.setTag(TAG_IMAGE_BTN_1);
imageBtn1.setOnClickListener(onClickListner_BTN_CLICK);
imageBtn2.setTag(TAG_IMAGE_BTN_2);
imageBtn2.setOnClickListener(onClickListner_BTN_CLICK);
.......................................................
.......................................................
}
OnClickListener onClickListner_BTN_CLICK = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int iTag = (Integer)v.getTag();
switch (iTag) {
case TAG_IMAGE_BTN_1:
break;
case TAG_IMAGE_BTN_2:
break;
case TAG_IMAGE_BTN_3:
break;
case TAG_IMAGE_BTN_4:
break;
}
}
};
}
The advantages of using the tag values for capture the action,
1)If we use R.id....... then we have to change the value in switch case if we change it in the xml file
2)We can use only one onClickListner for every action in an activity.

Categories