Accessing every textview within gridview and setting colour to white - java

Sorry if this is a weird question, I just really don't understand how to get this working.
basically, I want a behavior so that when you click one of my gridview items, it highlights red, This works fine, but I need it to only have 2 highlighted letters at a time from the click method.
Outside this method is
public void onItemClick(AdapterView<?>parent, View v, int position, long id)
{
//selection.setText(Words[position]);
}
This is inside my method which gets fired
public void onItemClick(AdapterView<?> arg0,View arg1, int arg2, long arg3)
{
Toast.makeText(getApplicationContext(), ""+arg2,Toast.LENGTH_SHORT).show();
((TextView) arg1).setTextColor(getResources().getColor(android.R.color.holo_red_light));
((TextView) arg1).setTextSize(9);
counter++;
if(counter == 2)
{
//this needs to select everything in the gridview and set to white
}
}
Does anyone have any ideas how I would go about it ( if it's even possible)

Sorted it.
if(counter == 3)
{
gridView.setAdapter(adapter);
// do the check if its a word or not
counter = 0;
}
works like a charm

Related

android how do i find out which view was clicked in a listview

im quite a newby to android and java. I created a my own adapter and listView and i want to know how do i find out which view or row was pressed in my listView so i can do a specific task for row was picked (task includes sending data and info to another activity).
I thought that maybe the position variable contains the name of the row clicked so i tried it but when a row is clicked the app crashes
hangarList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getApplicationContext(), position,Toast.LENGTH_SHORT);
}
});
can someone help
it could be that position is an integer, and it's expecting a string, and also the show() needs to be called on your toast to see the message.
hangarList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getApplicationContext(), position+"",Toast.LENGTH_SHORT).show();
}
});
First, you're on the right track regarding finding out which row was clicked.
The error lays in your use of Toast.makeText(). There are two versions of that method:
makeText(Context context, int resId, int duration)
makeText(Context context, CharSequence text, int duration)
Now in your vode you do Toast.makeText(..., position, ...) which invokes the first version of the method (as position is an integer), but because position is not a resource id the app crashes.
So, you have to use the second version and to do that, pass a CharSequence (or String) as second parameter: Toast.makeText(..., position+"", ...)
Btw. to get the actual value of the row, you can use hangarList.getItemAtPosition(position).
The views that make up the rows in the ListView are indexed like an array. The position value is the index of the row or view that was pressed. You can use the position value to look up the information associated with the clicked view.
Your app is crashing because Toast.makeText(Context, int, int) expects a string resource id integer for its second argument. When you give it the position as the id, it can't find that string resource and throws an exception. To display the index of the view that was clicked try:
hangarList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getApplicationContext(),
"View at position " + position + " clicked.",
Toast.LENGTH_SHORT);
}
}
Application crashes because of your Toast.You should use Toast like
Toast.makeText(context, text, duration).show();
And you can fix it in simple way just like this:
String positionString=Integer.toString(position);
Toast.makeText(getApplicationContext(), positionString,Toast.LENGTH_SHORT).show();
And there is no problem without Toast.As you say which item of listview is clicked?
For controlling which item is clicked You can use position variable of method.
Regards.. Omer

Enable/Disable RelativeLayout view(s) on Spinner select

I have three Relativelayout views set up in my XML one after eachother, in my onCreate method I have initialised all three views and setEnabled() to false. Then I have set up a Spinner and I want to enable each view when each respective button is clicked. Is there a way to do this? So far I have (on my Spinner):
public void onItemSelected(AdapterView<?> parent, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
if (parent.getItemAtPosition(position).equals("Quantity")) {
calSelectInt = 1;
calSeek.setEnabled(true);
calWeight.setEnabled(false);
calFlour.setEnabled(false);
} else if (parent.getItemAtPosition(position).equals("Dough Weight")) {
calSelectInt = 2;
calSeek.setEnabled(false);
calWeight.setEnabled(true);
calFlour.setEnabled(false);
} else if (parent.getItemAtPosition(position).equals("Flour Weight")) {
calSelectInt = 3;
calSeek.setEnabled(false);
calWeight.setEnabled(false);
calFlour.setEnabled(true);
}
}
The cal___ represents each view. The calSelectInt is an attempt to set an Integer for each and call in another method when each Integer is read.
As a result when run, all three views are viewed, any ideas? Why isn't setEnabled working? Or is my code poorly thought out. Thanks
Turns out I had to setVisibility(View.GONE) and (View.VISIBLE) instead of setEnabled(boolean). Strange, that method didn't seem to work for me in the past with other things but hey ho.

Drag and Drop in a `ListView`

I am trying to implement a drag and drop in a ListView in android(Ice Cream Sandwich). So when the dragged object reaches the edge of the ListView, I am scrolling the ListView in the relevant direction. The problem is that when we scroll, sometimes the adapter creates new Views as necessary and these 'new' Views did not receive the ACTION_DRAG_STARTED event earlier and hence do not receive the DragEvent updates. Is there any way I can send the events to these views as well?
An easiest way to implement drag and drop in listview is you use this great library.
https://github.com/commonsguy/cwac-touchlist
it's worth trying.
Looking at the source for View, I see:
static final int DRAG_CAN_ACCEPT = 0x00000001;
int mPrivateFlags2;
boolean canAcceptDrag() {
return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
}
mPrivateFlags2 is package-private and not exposed by the SDK. However, you should be able to change it in a subclass by doing:
try {
Field mPrivateFlags2 = this.getClass().getField("mPrivateFlags2");
int currentValue = mPrivateFlags2.getInt(this);
mPrivateFlags2.setInt(this, currentValue | 0x00000001);
} catch (Exception e) {
}
I have the same problem. I did not solved this recycling problem, but I found a possible workaround still using the Drag & Drop framework. The idea is to change of perspective: instead of using a OnDragListener on each View in the list, it can be used on the ListView directly.
Then the idea is to find on top of which item the finger is while doing the Drag & Drop, and to write the related display code in the ListAdapter of the ListView. The trick is then to find on top of which item view we are, and where the drop is done.
In order to do that, I set as an id to each view created by the adapter its ListView position - with View.setId(), so I can find it later using a combination of ListView.pointToPosition() and ListView.findViewById().
As a drag listener example (which is, I remind you, applied on the ListView), it can be something like that:
// Initalize your ListView
private ListView _myListView = new ListView(getContext());
// Start drag when long click on a ListView item
_myListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(null, shadowBuilder, _myListView.getItemAtPosition(position), 0);
return true;
}
});
// Set the adapter and drag listener
_myListView.setOnDragListener(new MyListViewDragListener());
_myListView.setAdapter(new MyViewAdapter(getActivity()));
// Classes used above
private class MyViewAdapter extends ArrayAdapter<Object> {
public MyViewAdapter (Context context, List<TimedElement> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View myView = convertView;
if (myView == null) {
// Instanciate your view
}
// Associates view and position in ListAdapter, needed for drag and drop
myView.setId(position);
return myView;
}
}
private class MyListViewDragListener implements View.OnDragListener {
#Override
public boolean onDrag(View v, DragEvent event) {
final int action = event.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
return true;
case DragEvent.ACTION_DRAG_DROP:
// We drag the item on top of the one which is at itemPosition
int itemPosition = _myListView.pointToPosition((int)event.getX(), (int)event.getY());
// We can even get the view at itemPosition thanks to get/setid
View itemView = _myListView.findViewById(itemPosition );
/* If you try the same thing in ACTION_DRAG_LOCATION, itemView
* is sometimes null; if you need this view, just return if null.
* As the same event is then fired later, only process the event
* when itemView is not null.
* It can be more problematic in ACTION_DRAG_DROP but for now
* I never had itemView null in this event. */
// Handle the drop as you like
return true;
}
}
}
Now if you need to have a visual feedback when doing a drag and drop, there are several strategies. You can for instance have 2 instance variables in your activity named:
private boolean ongoingDrag = false; // To know if we are in a drag&drop state
private int dragPosition = 0; // You put the itemPosition variable here
When doing the drag and drop in MyListViewDragListener you modify these variables, and you use their state in MyViewAdapter. Of course do not forget to update the UI (in the event thread of course, use a Handler) with something like _myListView.getAdapter()).notifyDataSetChanged() or maybe _myListView.invalidate() method.
The problem is because listView.getPositionForView(view) returns -1 if the view is not visible when it is called. So relying on that will fail when you scroll the list. So, instead of setting a view.setOnLongClickListener() you can set a listView.setOnItemLongClickListener() on the list item which calls startDrag() on the item. onItemLongClick() gives you the position which you can pass to in the myLocalState parameter of startDrag(). Then you recover that in onDrag() using event.getLocalState() and casting it to an Integer. Like this...
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
position -= listView.getHeaderViewsCount();
DragShadowBuilder dragShadow = new View.DragShadowBuilder(view);
view.startDrag(null, dragShadow, position, 0);
return true;
}
});
Then in your OnDragListener...
#Override
public boolean onDrag(View eventView, DragEvent event) {
Integer dragViewPos = ((Integer) event.getLocalState());
int eventViewPos = listView.getPositionForView(eventView) - listView.getHeaderViewsCount();
...
}

Java/Android, is it possible to get contents of an Object?

As the title suggests. I've done a bit of research and tried Jackson which seems like it should have worked but I had ridiculous amount of errors while trying to use it so that seemed a no go.
Basically my problem is this, I have my list view populated by an adapator as so:
friendsArrayAdapter = new FriendsArrayAdapter(
NetPlay.this, R.layout.rowlayout, friends);
listView.setAdapter(friendsArrayAdapter);
friendsArrayAdapter.notifyDataSetChanged();
and Then I want to handle onClick events within this listview, to copy the contents of that list view to a variable:
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Object o = listView.getItemAtPosition(position);
Object o = arg0.getItemAtPosition(position);
//mText.setText(o);
}
});
Now this all works fine, but the value returned is the actual Object ID/Reference
Shows as something#Friends.21312. What I want is the actual contents which should be a Name + ID.
Is this even possible or do I need to redo my whole list view population?
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//friends is the array that is given to the Adapter.
//given friends = Friend[]
Friend f = friends[position];
f.getName();
f.getID();
}
This is only a guess, please post your whole code for better help!

Android spinner "onclicklistener" question

I am working with Spinner, cursors and adapters.
I want to setup a click listener for the spinner so that once a user selects an item from the spinner it gets the current selected item and then carrys out some other tasks ( all this extra code is fine, its just 1 problem I am having).... It kind of works, however, once I declare the setOnItemSelectedListener callback, since the cursor has already been populated, the event is fired as soon as the app launches.
I guess I need a way to define the cursor without selecting an initial item so that the event doesnt fire (since an item will not be selected). Or is there another better way to achieve this?
Basically, as it stands, once the app loads the setOnItemSelectedListener function is firing because the cursor is being populated ( i think). Moreover, ignoreing the fact that the event is firing too soon, if I then select the -same- item in the spinner, it doesnt fire the event sincethe item didnt change. SHould I be using a different callback instead of setonitemslectedlistener? Here is the code I have so far.
c = db.getallrecents();
startManagingCursor(c);
busnumspinner = (Spinner) findViewById(R.id.Spinner01);
SimpleCursorAdapter spinneradapter = new SimpleCursorAdapter(this,
R.layout.lvlayout, c, spincol, spinto);
busnumspinner.setAdapter(spinneradapter);
busnumspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String spinnerString = null;
Cursor cc = (Cursor)(busnumspinner.getSelectedItem());
if (cc != null) {
spinnerString = cc.getString(
cc.getColumnIndex("busnum"));
text = spinnerString;
}
showDialog(DATE_DIALOG_ID);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
This has already been discussed in this question. Look there, though it has a similar answer like the one given by blindstuff.
EDIT:
If the onItemSelectedListener is not firing when you need it, then you probably need a onClickListener in eachtext item of the droplist and get in there the current position of the selected item of the spinner. The problem is that as it is said here spinner don't support this event, but maybe you can get it by doing something similar to the explained in this stackoverflow question. I haven't tried it so I'm not sure it will work.
Use a boolean flag to ignore the first time it gets selected by the system, its not a pretty solution, but i've struggled with this a couple of times, and never found a better solution.
you can add first item of spinner by default value like selectvalues and check its position in onitemselected listener, if it's zero position then dont enter in the loop greater than 0 then enter in the method
see the example
busnumspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int
position, long id) {
if(position!=0)
{
String spinnerString = null;
Cursor cc = (Cursor)(busnumspinner.getSelectedItem());
if (cc != null) {
spinnerString = cc.getString(
cc.getColumnIndex("busnum"));
text = spinnerString;
}
}
So this is not run the default value
Try this:
Extend your SimpleCursorAdapter, override bindView() and set OnClickListener for the row view.
This will overcome both issues: You do not get the initial call, and you get each selection click (inc. re-selection)
Let me know if you need example code.
EDIT: Code example:
protected class NoteAdapter extends SimpleCursorAdapter {
// Constructor
public NoteAdapter(Context context, Cursor c) {
super(context, R.layout.etb_items_strip_list_item, c, fromNote, toNote);
}
// This is where the actual binding of a cursor to view happens
#Override
public void bindView(View row, Context context, Cursor cursor) {
super.bindView(row, context, cursor);
// Save id
Long id = cursor.getLong(cursor.getColumnIndex("_id"));
row.setTag(id);
// Set callback
row.setOnClickListener(row_OnClick);
}
// Callback: Item Click
OnClickListener row_OnClick = new OnClickListener(){
public void onClick(View v) {
Long id = (Long) v.getTag();
}
};
}

Categories