I want to include many buttons in my app, which can play a sound by clicking, so I included an OnClick event.
#Override
public void onClick(View view) {
int id = view.getId();
final MediaPlayer mediaPlayer = new MediaPlayer();
switch (id) {
case R.id.whisteling_bird:
stopandPlay(R.raw.whisteling_bird, mediaPlayer);
break;
default:
break;
}
}
But now I have the following problem:
I also want to change the Alpha value of the button by using
.getBackground().setAlpha(64);
But what do I have to write before .getBackground()?
I donĀ“t want to write this
final Button whisteling_bird = (Button) view.findViewById(R.id.whisteling_bird);
whisteling_bird.setOnClickListener(this);
whisteling_bird.getBackground().setAlpha(64);
for every single button. What can I do?
In your onClick(), below id line,
put view.getBackground().setAlpha(64);
it will set every clicked view's alpha to 64. But you will also need to reset it somewhere for safety.
Related
Currently I am working on an app that has somewhat of a basic calculator layout and functions. I have 8 edittext and a grid of 9 buttons. With the onClicklistener method is there a better way of handling this instead of nesting a long if or switch statement for each Edittext?
private View.OnClickListener mListener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId() /*to get clicked view id**/) {
case R.id.btn_1:
if edt_1.hasFocus() {
edt_1 = btn_1.getText()
}
if edt_2.hasFocus() {
edt_2 = btn_1.getText()
}
break;
case R.id.btn_2:
if edt_1.hasFocus() {
edt_1 = btn_1.getText()
}
if edt_2.hasFocus() {
edt_2 = btn_1.getText()
}
break;
default:
break;
}
}
I was thinking maybe it would be better to use a hasFocus() method and listen for clicks from there or a while loop, then maybe pass a variable?
Thanks in advance..
Hear is a way where you can small your code. just add android:onClick="onClick" in every button of your grid layout and do following in java file,
public void onClick(View v) {
Button b=(Button)v;
String s+=b.getText();
}
This two line get text from your button and set to the String s.
if you want to create calculator that function real-time calculation like this calculator
APK:https://play.google.com/store/apps/details?id=com.androchunk.calculator
then you can find free source code of calculator project as well as tutorial video that help you to create calculator and understand working of calculator.
Tutorial videos:https://www.youtube.com/playlist?list=PLdMmtAIsH0KYiKrdpbzat6t96Nb1_k3_1
I have seen lots of example to which one use a if condition or a case statement to programmatically change the conditions of elements...yadda yadda. I need to change the value of a button based on what the user clicks. Below is the code that I currently have.
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){CONTINUES TO OTHER FUNCTIONS }
I basically need to know what button was pressed. Then dynamically populate it into findViewById() function. i.e.
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
This way by the time it gets to the final Button part of the code it will have the value to which the user clicked on. Code works if I only want to have one button or a page mile deep in different configuration (not ideal).
All the examples I have seen so far are after the user clicks the button (which is what I want) but they name the buttons name statically like above code shows but very much static.
Hope that all makes sense.
UPDATE:
I think I may have confused the situation. Below is the remaining code. Hopefully this will provide context. The btnOpenPopup needs to remain the same as it's used in the call to execute the command for a new window to actually popup. Hopefully this will provide a bit more context for what I'm trying to achieve.
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.meditationpopup, null);
//set the title of the popup
TextView titletext = (TextView) popupView.findViewById(R.id.chakratitle);
titletext.setText(activityName);
if (activityName.equals("Root"))
{
switch (arg0.getId())
{
case R.id.color:
//Rename the string so to get the value from the string xml
String stringName = activityName.toLowerCase().replaceAll(" ","")+"color";
TextView desctext = (TextView) popupView.findViewById(R.id.popupDesc);
desctext.setText(getString(getStringResource(getApplicationContext(),stringName)));
break;
case R.id.polarity:
//Rename the string so to get the value from the string xml
String polarityString = activityName.toLowerCase().replaceAll(" ","")+"polarity";
TextView polarityDesc = (TextView) popupView.findViewById(R.id.popupDesc);
//polarityDesc.setText(activityName);
polarityDesc.setText(getString(getStringResource(getApplicationContext(),polarityString)));
break;
}
}
I think
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
should be
Button btnOpenPopupFirst = (Button)findViewById(R.id.polarity);
Button btnOpenPopupSecond = (Button) findViewById(R.id.color);
you should declare different different button for diffrerent findviewbyid
also in my eclipse it is not accepting
btnOpenPopup.setOnClickListener(new Button.OnClickListener()
instead it works with
btnOpenPopup.setOnClickListener(new View.OnClickListener() {}
and you need to provide more clear view of what you want to perform
new thoughts,try doing this:
btnOpenPopupFirst.setOnClickListener(this);
btnOpenPopupSecond.setOnClickListener(this);
then option will come on both the above code lines
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (MainActivity)
choose this
let MainActivity implement OnClickListener
then this option will come
The type MainActivity must implement the inherited abstract method View.OnClickListener.onClick(View)
choose
add unimplemented method
now
#Override
public void onClick(View v)
will be created
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.polarity:
Toast.makeText(getApplicationContext(), "btnOpenPopupFirst(polarity) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
break;
case R.id.color:
Toast.makeText(getApplicationContext(), "btnOpenPopupSecond(color) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
default:
break;
}
}
And post your views after implementing this way.
int[] id={R.id.button1,R.id.button2};
Button b=(Button)findViewById(id[i]);
The onClick method in Button.OnClickListener has a View parameter... you can call getId() on that view to get the id of that button that was clicked on.
It doesn't make too much sense to me. If what you really want is this:
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
All you need to do is set your value in the onClick(View view) method of your OnClickListener
public void onClick(View view) {
btnOpenPopup = (Button)view;
}
Android 2.3.3
I have a table with N rows and N columns. For each row, I should add 4 buttons dynamically, and later do actions based on the button clicked. I know we can set the button IDs with Integer values with button.setID(), but I want to know whether we can set IDs as string values as we set in XML files, such as btnXYZ1 and btnXYZ2 etc.,
You can use tags for that purpose . For example
btn.setTag("btXYZ");
for (int i=0;i<nob;i++) {
Button btn = new Button(this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setOnClickListener(btnclick); <<<<<<<set click
btn.setLayoutParams(lprams);
dynamicview.addView(btn);
}
And add this listner outside the any method and inside class
OnClickListener btnclick = new OnClickListener() {
#Override
public void onClick(View view) {
switch(view.getId()) {
case 1:
//first button click
break;
//Second button click
case 2:
break;
case 3:
//third button click
break;
case 4:
//fourth button click
break;
.
.
.
default:
break;
}
}
};
The strings you use in your XML files correspond to an int in R.java, and are hence actually ints. The setId() method will only accept an int value as an argument. You could define your IDs in a constants file, something like:
public class Ids {
public static final int ID_ONE = 1;
}
and then use it as:
button.setId(Ids.ID_ONE);
No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value
No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value
If you have the references to the views anyway , you can simply save them all into a HashMap, for example using HashMap .
Another alternative , so that you will avoid any typos , is to have an enum as the key of the hashMap , for example : HashMap .
Im going to write some android app, which will basically consists of two activities. So first should have a lot of buttons (100+) and on click on any of them I will just get some special id and move to second activity. But is there any alternative to declare that hundreds of buttons and copy/paste one piece of code to every of them setting almost same onClickLister? Is there any special construction? Thanks
Edit: every of buttons are actually indexed from 1 to n. And on the click second activity will be launched and get that index to show it. I cant basically use any spinner or smth else, because there will be 3 rows of clickable things and each of them carring different images
Edit 2: so, to give you an idea, im going to do some table of buttons like in Angry Birds menu when you actually choosing the level you want to play. So, on click you will get id of button and start second activity
Call the method to add buttons
private void addButton(){
LinearLayout view = (LinearLayout) findViewById(R.id.linear_layout_id_here);
Button btn = null;
int w = 50;
int h = 25;
for(int i=1; i<100; i++) {
btn = new Button(this);
btn.setLayoutParams(new LayoutParams(w,h));
btn.setText("button " +i);
btn.setTag(""+i);
btn.setOnClickListener(onClickBtn);
view.addView(btn);
btn = null;
}
}
Call this method for handling onclick on button
private View.OnClickListener onClickBtn = new View.OnClickListener() {
public void onClick(View view) {
final int tag = Integer.parseInt(view.getTag().toString());
switch (tag) {
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
default:
break;
}
}
};
You should use a ListView.
ListViews are great for handling a lot of items at the same time. They are also natural for the user. Additionally, you use only one click listener - OnItemClickListener.
There's a useful example on how to work with ListViews in the Android Referenence.
You may add buttons in code, something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
/*your code here*/
GroupView gw =findViewById(R.id.pnlButtonscontainer); //find the panel to add the buttons
for(int i=0; i<100; i++) {
Button b = new Button(this);
b.setLayoutParameters(new LayoutParameters(w,h));
b.settext = i+"";
b.setOnClickListener(new OnClickListener(){
});
}
}
I coded directly into browser, so some syntax error may appear in my code, but this is the point, a way, not the only one, to add 100 buttons.
I have a null pointer on a button that I need to take me to a new layout when pushed. I have the code set as:
((Button) findViewById(R.id.analyzee)).setOnClickListener(btnClick);
inside a method that uses conditional statements.
It is a basic face detect app. If faces are not found, I do this:
if (facesFound < 1) {
mFlipper.setDisplayedChild(2);
mTheMessage = (TextView) findViewById(R.id.falsemessage);
mThePicture = (ImageView) findViewById(R.id.false_view);
mTheMessage.setText(R.string.noFaceOne);
mThePicture.setImageBitmap(bitmap565);
return;
if faces are found, I draw a box on the face, and do this:
mFlipper.setDisplayedChild(1);
mTheMessage.setText(R.string.noFaceFive);
mThePicture.setImageBitmap(bitmap565);
My issue lies here though, I use this method to run when buttons are clocked:
private final View.OnClickListener btnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.scan_box:
openCamera();
break;
case R.id.crop_face:
final ProgressDialog dialog = ProgressDialog.show(Main.this, "",
"Cropping photo", true);
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
}, 3000);
cropFace();
break;
So, my issue lies in this:
In one of my layouts in the flipper, the button that rests on the layout will need to give the user the option to snap a new picture if there are no faces found. The other layout will need the button (upon click) to have the faces cropped and the results to be sent to another layout.
The issue I am facing is where the code:
((Button) findViewById(R.id.crop_face)).setOnClickListener(btnClick);
needs to be placed in order for the program to release the button has been clicked, it calls the case in my switch statement, and runs the crop face_method.
I try putting it in the if statement where I set the image View and text View, but I get a null pointer on that line I am declaring my button on.
The buttons I have on my main menu work fine, as they are in my onCreate method, but I don't know where to play this button command, and also where I need to place my reopen Camera command.
Thanks!
I simply was using the wrong button ID...sorry for the confusion =x