Android - pass dynamic data to onClick - android

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).

Related

Made a method each for multiple Spinners - how to pass this data on to new activities?

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.

Get the listItem ID in a onClick method of SetOnClickListener method of an adapter?

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
}
});

How do you keep layouts clicks correctly referenced?

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?

Android method paramater variable meaning/use?

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!
}
}
}

How to handle events from a CheckedChangedListener in a ListView

Iv'e got a custom Listview implemented in this particular class, it looks like
[Image/Textview/Checkbox]
When someone clicks on the text is should launch another class, this is working at the moment, however when someone clicks a checkbox I want to update an array that stores the current state of all the checkboxes, I tried doing that via using a onCheckedChanged method within the custom adapter however it doesn't work as the position variable isn't final. So two questions
1 within the adapter is their a way to get the position of the Checkbox so I can change the right position in the array, and
2 If not is their another way to update the array somewhere else without disrupting the current functionality of the onClick.
Here is my onCheckedChanged within my adapter
CheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton but, boolean b) {
// TODO Auto-generated method stub
if(but.isChecked())
{
deleteList[???] = true;
}else{
deleteList[???] = false;
}
}
});
Have a look a this method. You can set a tag to a view containing any object you wish, which in your case may be the integer value associated with the CheckBox's row.
So when you create your CheckBox:
but.setTag(new Integer(position));
This would change your if statement to:
if (but.isChecked()){
deleteList[((Integer) but.getTag()).intValue()] = true;
} else {
deleteList[((Integer) but.getTag()).intValue()] = false;
}
Let me know if this helps!

Categories

Resources