beginner here.
First off, this question arrived while i was trying to implement button clicks using android:onClick in xml and referencing a method.
Now, when you reference a method, the parameter of the method in the activity must be "(View)". Quick question, what is the variable after the word View in the method parameter? Usually it's like "(View v)" or "(View view)". What is the second variable in the parameter, can it be anything? When is it used? Just want general info about it, couldn't really find such specific info anywhere.
Thanks in advance
I think you misunderstood. The first parameter in (View view) is the type of the parameter, and the second is the temporary name supplied to it (it is just a dummy name, so you can use whatever you like). For example, if I have to pass an integer as parameter, I would use (int i), where i is understood to be of type int. So, in your case an object of type View is temporarily called view to be passed as parameter into a function.
This is reference to the view you are clicking. Take a look at the question here, and you may find when to use it.
So you are asking about onClick()?
This method is from View.onClickListener interface, you can see the document in http://developer.android.com/reference/android/view/View.OnClickListener.html
Because it is an interface, so there will be only paramater :View, it represents the view you just clicked. for example, if you set a button into the interface, it means button, if you set a ImageView into the interface, it means the ImageView itself;
For example:
YourActiivty extends Activity implements View.OnClickListener {
public void onCreate(Bundle onSaveInstance) {
super.onCreate(onSaveInstance);
setContentView(R.layout.yourlayout);
//your button, we assume id is R.id.yourbutton;
Button yourbutton = (Button) findViewById(R.id.yourbutton);
yourbutton.setOnClickListener(this);
//your imageview, we assume id is R.id.yourimageview;
ImageView yourImageView = (ImageView) findViewById(R.id.yourimageview);
yourImageView.setClickable(true);
yourImageView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
if(id == R.id.yourbutton) {
//your button is clicked!
} else if(id == R.id.yourimageview) {
//your imageview is clicked!
}
}
}
Related
This might sound a bit convoluted.
I have roughly 15 Spinners in one activity and made a distinct method for each of these spinners. I then initiate the methods in the onCreate method.
Method example:
//Relative Position Spinner
public void relativePositionSpinner() {
Spinner relativePositionSpinner = (Spinner) findViewById(R.id.spinner_relativePosition);
ArrayAdapter relativePositionAdapter = ArrayAdapter.createFromResource(this, R.array.relativePosition, R.layout.spinner_item);
relativePositionSpinner.setAdapter(relativePositionAdapter);
//what happens when selected
relativePositionSpinner.setOnItemSelectedListener(this);
}
OnCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_hand);
//initiate all Spinners
relativePositionSpinner();
absolutePositionSpinner();
etc.
Now what I want is to send the data of each Spinner to another Activity with the click of a Button. I know that I can do this with an intent and using putExtra in the Button method like this:
public void openHandSummary() {
//Find the Button that gives option to enter new hand
Button handInputButton = (Button) findViewById(R.id.hand_input_button);
//set a click listener on Hand Analyzer Button
handInputButton.setOnClickListener(new View.OnClickListener() {
//below code will be executed when the new Hand Button is clicked
#Override
public void onClick(View view) {
Intent handSummaryIntent = new Intent(NewHandActivity.this, HandSummaryActivity.class);
handSummaryIntent.putExtra("RelPosString", WHATTOENTERHERE??)
startActivity(handSummaryIntent);
}
});
}
However I do not know how to retrieve the value/variable out of my Spinners to put them into the Button/intent method? Because if I make a String in the Spinner method, then I can't access this in the Button method.
So I feel like I have too many methods? So is there a way to pass data from one method to another method, or do I have to cancel some methods? What would be the easiest way to set this up?
I also made an onItemSelected to make some toasts, which worked. Can I use OnItemSelected somehow to create variables or initiate a data transfer to another Activity?
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView myText = (TextView) view;
switch (parent.getId()) {
case R.id.spinner_relativePosition:
makeText(NewHandActivity.this, "Relative Position is " + myText.getText(), Toast.LENGTH_SHORT).show();
break;
case R.id.spinner_absolutePosition:
makeText(NewHandActivity.this, "Absolute Position is " + myText.getText(), Toast.LENGTH_SHORT).show();
break;
I'm very new to coding, and I just can't figure out the logic how I get the Spinner methods, Button/iniate method and OnItemSelected method to work together and exchange variables. Would appreciate if someone can point me in the right direction. Have already browsed the internet a day or so to find an answer, with no success.
I like your idea of separating out the code to create each spinner into its own method. However, if you are copying and pasting the whole method and making a few changes, you should step back and think about how you can do it even more easily. Often the changes you make after copy and paste give a hint that you should add some parameters to the method. If you do it correctly, you can write just a single method and then copy and paste the method call instead of the entire method and then make appropriate changes to the arguments.
As for your actual question, you are making this much more complicated than necessary. Specifically, you do not need to setOnItemSelectedListener() on any of the Spinners. Instead, the OnClickListener for the button should just get the selected item from each spinner and send it to the new activity in the Intent.
I have an activity which lists objects from an array objects through a custom adapter. The row of this adapter contains several EditText's and a layout which is clickable and does the deleting of that object selected. My intention is the object can be updated by clicking on the item (which shows another activity) and deleting by clicking on the layout. So that, I have to implement the updating and the deleting by differents setOnItemClickListener's.
I have done the updating just setting an setOnItemClickListener to the listView of objects and sending the whole object to a new activity through putExtra and getIntent.
The problem is with the deleting. I have implemented an OnClickListener directly on the adapter, like this:
holder.layoutEliminar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Here call to an Async Task to delete the object but, what about t the id object???
}
That code goes fine when I click on the layout of the row but I don't know the way to obtain the id of the object selected in the listView. Does anybody know how??
Do not hesitate to ask me for more code or details.
Please excuse my English, not native.
You can set a tag for the view on your getView:
holder.layoutEliminar.setTag(theIdOfYourObject);
Note that View.setTag(Object tag) takes an Object as parameter (documentation). I will assume that you want to set the id of the object to delete as String for the tag.
And then, on your onClick
holder.layoutEliminar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout layoutEliminar;
// Retrieve your layoutEliminar from v
// ...
// Get the id of the object to delete from the tag
String id = (String) layoutEliminar.getTag();
}
};
I already did with the help of #Antonio. I didn't use Tag's, I have used the instruction getItem(position).getId() into the method onClick to refer the id of the object (don't know if it's the best and more efficient way to do). Like this:
holder.btnEliminar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("PedidosAdapter dd: ",String.valueOf(getItem(position).getId()));
//Async Task for deleting the object with that ID
}
});
This sounds like the other questions, but it actually is a little different. So my scenario is, I have six buttons and the user can click any of them => but I want to keep track of the ORDER by which the buttons were clicked. So here's what I did. I saved a record in SQLite and using the date, I can determine the order the buttons were clicked. Is there another way to do this?
public class ButtonClickListener implements OnClickListener {
#Override
public void onClick(View v) {
// I want to be able to pass data in this method.
try {
v.setVisibility(View.INVISIBLE);
} catch (Exception ex) {
}
saveClickDAO(); // has Date field to sort later
}
Is there a way to actually pass data to this onClick event? I know I can add data using a parameter to the constructor here, but that would be data that is static already.
You have a View v in your onClick(View v), so you can use data on the View. v.getId() or v.getTag() will give you some view related data.
v.getId() will give you the android:id you set in your layout xml, such as R.id.some_btn
v.getTag() will give you the object you set with v.setTag(Object o).
Let me explain myself:
As you know, when you've a view which have to be inflated several times, but changing values, you use a GridView or a ListView. Those two Composite views, have some methods like onItemClick. This method is so useful, as it returns the position of the view clicked.
With this position you can perform some concrete tasks, like retreiving from an ArrayList, the information of that object. Here's an example:
ArrayList<DocumentInfo> documents;
And when you set a setOnItemClickListener() you can get the correct values:
gallery.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos, long arg3) {
getDocumentInfoOf(pos);
}
});
public void getDocumentInfoOf(int position){
DocumentInfo doc = documents.get(position);
}
However, when you aren't using a GridView or a ListView, you're in your own. You don't have a clear way (AFAIK) to know which layout inflated is the one clicked (I mean like the previous example, the "position" value).
What I am currently doing, is the following:
for (int i=0; i<10;i++){
RelativeLayout documentInflated = (RelativeLayout) this.mInflater.inflate(R.layout.open_document_per_inflar, null);
documentInflated.setContentDescription(""+i);
documentInflated.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
openDocument(v);
}
});
container.addView(documentInflated);
}
public void openDocument(View v){
int idDocument = Integer.parseInt(v.getContentDescription());
//idDocument is the view clicked
}
Do you guys think this is a clear way of doing this?
Thank you!!!
If I'm not mistaken you want to get some data from your created Relative Layout when you click on it. The best solution here is to use the method setTag(Object tag). After that you get the informatiom with the method getTag(). This method allows you to add extra information to your view. As it says in the documentation:
Tags
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.
Also depending on your needs you can seperate every tag with a key -> value pair with the method setTag(int key, Object tag), after that you can retrieve this object with getTag(int key);
So in your case you will have
documentInflated.setTag(i)
in the onClick yo will then have:
int i = (int)v.getTag();
Unless I'm not understanding your desire...
#Override
public void onClick(View v) {
openDocument(v);
}
v IS the view being clicked. Your code looks like it should do what you're hoping it will do. What are you actually seeing happen?
Here's the situation: I have an activity that dynamically generates a bunch of randomized custom imagebuttons and adds them to TableRows, in a TableView, in my xml. This activity also has a method that I want to call when one/any of these buttons is clicked. The buttons have variables inside them; the method gets these variables and sets them into a TextView (in the same activity) so I figure all the buttons can use this one method. If these buttons were defined in the XML I would just use android:onClick="displayCell" to specify the method, but they aren't. Is there a way to just set onClick for these buttons as I'm generating them in the activity or do I have to use
button.setOnClickListener(new OnClickListener(){....});
and go through a bunch of hassle as I've seen in some of the answers around here? The problem I have with that is that I can't seem to call my method from inside onClick because the argument of the method (the button) is not final (I'm making a bunch of 'button' in a loop so I don't think it can be):
button.setOnClickListener(new OnClickListener(){
public void onClick(View q){
button.getActivity().displayCell(button);//I want to do something like this but this obviously doesn't work
}
});
You can have the Activity implement OnClickListener and then (assuming you are in the activity):
button.setOnClickListener(this);
Yes as comodoro states, or make your onClickLIstener a member variable of your class, don't do a "new" on each button.
private OnClickListener mOnClickListener = new OnClickListener() {...};
and when creating your buttons:
button.setOnClickListener(mOnClickListener);
The onClick() function in your listener will be passed the View of the button itself. You can access the buttons variables, etc, from this function.
public void onClick(View v)
{
ImageButton button = (ImageButton)v;
// and access your button data via button object...
}
A solution to this could be :
Create different instances of buttons .(So you can make them final)
Use setId() method to give them an integer ID (to refer to them later).You can store the ID's in an a Listto refer them later on.
Define their onClickListeners right after you create it.
Try using a class that inherits from button and add there the OnClickListener. Like this:
class MyButton extends Button {
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
displayCell(v);
}
};
}