Here is my buttonAdapter class that i think is accurate:
package com.example.test;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
public class ButtonAdapter extends BaseAdapter {
private Context mContext;
public String [] fName = { "File 1", "File 2", "Roflcopters"};
// Gets the context so it can be used later
public ButtonAdapter(Context c) { mContext = c; }
// Total number of things contained within the adapter
public int getCount () { return 8; }
// Require for structure, not really used in my code.
public Object getItem (int position) { return null; }
// Require for structure, not really used in my code. Can be used to get the id of an item in the adapter for manual control.
public long getItemId (int position) { return position; }
public View getView (int position, View convertView, ViewGroup parent){
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn = new Button (mContext);
btn.setLayoutParams (new GridView.LayoutParams (190, 190));
btn.setPadding (1, 1, 1, 1);
} else {
btn = (Button) convertView;
}
// btn.setText(filesnames[position]);
// filenames is an array of strings
//btn.setTextColor (Color.WHITE);
//btn.setBackgroundResource (R.drawable.sample_2);
//btn.setBackgroundColor (Color.BLACK);
btn.setHighlightColor(Color.GREEN);
btn.setId (position);
return btn;
}
}
Here is my home class. I can't get the onItemClick to work out. What am I doing wrong here:
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
public class home extends Activity implements OnItemClickListener {
public final static String EXTRA_MESSAGE1 = "com.example.text.MESSAGE";
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_home);
GridView gridview = (GridView) findViewById (R.id.gridview);
gridview.setAdapter (new ButtonAdapter (this));
/*gridview.setOnItemClickListener (new OnItemClickListener () {
public void onItemClick (AdapterView <?> parent, View v, int position, long id) {
Toast.makeText (home.this, "" + position, Toast.LENGTH_LONG).show ();
Intent intent = new Intent (this, alarm.class);
String message = "Position:" + position;
intent.putExtra(EXTRA_MESSAGE1, message);
startActivity (intent);
}
});
* */
}
#Override
public void onItemClick (AdapterView <?> parent, View v, int position, long id) {
Intent intent = new Intent (this, alarm.class);
String message = "Position:" + position;
intent.putExtra(EXTRA_MESSAGE1, message);
startActivity (intent);
}
}
The onItemClick doesn't work and neither does the commented 'setOnItemClickListener' when it isn't commented out and 'onItemClick' is commented. What am I doing wrong?
If GridView, ListView have click able controls like BUtton, then onItemClick will not fired.
You need to implement Button Click listener in your getView method of the adapter.
like
public View getView(int position, View convertView, ViewGroup parent) {
Button btn;
if (convertView == null) { // if it's not recycled, initialize some
// attributes btn = new Button (mContext);
btn.setLayoutParams(new GridView.LayoutParams(190, 190));
btn.setPadding(1, 1, 1, 1);
} else {
btn = (Button) convertView;
} // btn.setText(filesnames[position]); // filenames is an array of
// strings //btn.setTextColor (Color.WHITE);
// btn.setBackgroundResource (R.drawable.sample_2);
// btn.setBackgroundColor (Color.BLACK);
btn.setHighlightColor(Color.GREEN);
btn.setId(position);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Handle the click here
}
});
return btn;
}
You can add this line in the root layout of GridView items:
android:descendantFocusability="blocksDescendants"
Then onItemClickListener.onItemClick() will not fire when you tap on subviews which OnClickListener has been defined for them separately.
I've tested that Set Button.onClickListener() (in API 15) won't solve the problem.
So the GridView will not trigger onItemClick if it contains clickable views.
You can use ImageView instead Button.
i have the same problem when i was trying to implement onitemclick on gridview where filled with button. Because the button is stealing the focus of each space on gridview, you have to give the inflated button android:focusable="false" . however, the button is taking up almost entire space inside a grid, so you have to click the very edge of the button to trigger onitemclick call-back. i am suggesting you can set onclick or use image and designe it like a button.
Related
I have made a custom View which contains an ImageView, a TextView and a delete Button.
I want to reset the particular View when I click the delete Button associated with it.
Please tell how to implement this.
Here is my MainActivity.java
package com.khurana.nikhil.list1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ListView lv;
TextView tv1, tv2;
View v1;
public String[] s = {"nikhil", "mukul", "kunal"};
public int[] img = {R.drawable.rty, R.drawable.sf, R.drawable.rty};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
CustomAdapter cad = new CustomAdapter(MainActivity.this, s, img);
lv.setAdapter(cad);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View v,int position,long id)
{
Toast.makeText(MainActivity.this,"You clicked "+s[position],Toast.LENGTH_SHORT).show();
}
});
}
}
Here is CustomAdapter.java
package com.khurana.nikhil.list1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<String>{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
return v;
}
}
((LinearLayout)yourView.getParent()).removeView(yourView);
or you can call from the layout directly
yourRelativeLayout.removeView(yourView)
I would recommend to use an ArrayList instead of a String[] in your Adapter class. It makes it a lot easier to delete or edit a View and the associated data behind it. I used this post to convert your String[] to an ArrayList, delete the item and convert back to String[].
This should work on button click:
In your Adapter class:
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int positionToRemove = v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(i);
strings = new String[a.size()];
s1= a.toArray(strings);
notifyDataSetChanged(); //refresh your listview based on new data
}
#Override
public int getCount() {
return s1.length;
}
#Override
public String getItem(int position) {
return s1[position];
}
View visibility to GONE will not delete your view from memory as well. Please be specific, do you want to retain your view for future?
If you are working in a listview you should call notifyDataSetChanged() the adapter. your getView() method can be like:
action on button can be like this
Button bt=(Button)v.findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s1 = ArrayUtils.remove(s1, position);
s2 = ArrayUtils.remove(s2, position);
notifyDataSetChanged();
}
});
If you want the view to disappear:
yourView.setVisibility(View.GONE);
EDIT: To get the parent view of the button: Android: Making changes to a button's parent view
Can someone please help me? I am trying to access a "position" variable itemclicked. I want the content of the other class to display a different thing depending on the list I clicked.
What I want is this: if I click position 0, then it takes me to another page and the TextView I created on that class changes to "you clicked position 0". If I click position 1, it changes to "you clicked position 1", etc.
I've attempted to do this, but it only works when I click position 0. If I click item 1, it shows "you have clicked position 0". I am very confused. I have tried using putexraa and other methods, but they are not working. Your help would be greatly appreciated.
package com.obi.arinzeapp;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private List<list> mymusic = new ArrayList<list>();
public list currentsong;
public int man;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populatemusiclist();
populateListView();
registerclick();
}
private void registerclick() {
ListView mus = (ListView) findViewById(R.id.musiclistview);
mus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long arg3) {
man = position;
try {
Class ourClass = Class.forName("com.obi.arinzeapp.Music");
Intent ourIntent = new Intent(MainActivity.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
private void populatemusiclist() {
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constance\"",
R.drawable.medi));
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constnce\"",
R.drawable.medi));
mymusic.add(new list(R.drawable.ff, " Mr.J.Mederiors \"Constnce\"",
R.drawable.medi));
}
private void populateListView() {
ArrayAdapter<list> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.musiclistview);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<list> {
public MyListAdapter() {
super(MainActivity.this, R.layout.viewitem, mymusic);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View veiwitem = convertView;
if (veiwitem == null) {
veiwitem = getLayoutInflater().inflate(R.layout.viewitem,
parent, false);
// return super.getView(position, convertView, parent);
}
list currentsong = mymusic.get(position);
ImageView imageview = (ImageView) veiwitem
.findViewById(R.id.imageView2);
imageview.setImageResource(currentsong.getNum());
TextView wor = (TextView) veiwitem.findViewById(R.id.word);
wor.setText(currentsong.getNameofsong());
ImageView imageview2 = (ImageView) veiwitem
.findViewById(R.id.imageView1);
imageview2.setImageResource(currentsong.getPicture());
return veiwitem;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
import android.app.Activity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Music extends Activity{
TextView name,song,album,about;
String nam,son,albu,abou;
RelativeLayout picc;
public int ye ;
MainActivity maa = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stu
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
name= (TextView) findViewById(R.id.name);
song= (TextView) findViewById(R.id.song);
album=(TextView) findViewById(R.id.album);
about=(TextView) findViewById(R.id.about);
picc=(RelativeLayout) findViewById(R.id.picc);
maa.man= ye;
if(ye==0){
name.setText("You clicked position 1") ;
}else{
name.setText("You clicked position 2") ;
}
}
}
Pass the value of man in putExtra while setting the intent for that class in mainActivity
Class ourClass = Class.forName("com.obi.arinzeapp.Music");
Intent ourIntent = new Intent(MainActivity.this, ourClass);
ourIntent.putExtra("man",man);
startActivity(ourIntent);
And get this extra in Music Activity
extras = getIntent().getExtras();
newInt= extras.getInt("man");
This is the standard way to pass the values from one activity to another.
But the way you doing you can try making man as static variablebut it is not recommended.
Hello to all great developers and helpers. I need some help.
I have gridview with defined icons. (They stored in application, i dont need to download them from internet).
1st Question - How to add textview (i.e Name of the Icon) to the existing gridview adapter?
2nd Question (Most important, first priority to solve) - How can i add specified urls for each item and clicking on it user will download specified file? (E.g - My gridview shows Skins, clicking on it user will be able to download the skin which he choose.)
I tried many ways, cannot find the solution.
Something like that:
public void prepareList()
{
listHttp = new ArrayList();
listHttp.add("http://yoursite/file1.apk");
listHttp.add("http://yoursite/file2.apk");
listHttp.add("http://yoursite/file3.apk");
SkinsActivity.class
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import java.util.ArrayList;
public class SkinsActivity extends Activity {
com.htc.widget.HtcAlertDialog.Builder builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
HtcAlertDialog.Builder alertDialog = new HtcAlertDialog.Builder(SkinsActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Installation");
// Setting Dialog Message
alertDialog.setMessage("Do you want to install this skin?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_about);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
ImageAdapter.class (Gridviewadapter)
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.sense5, R.drawable.sense5red,
R.drawable.concrete, R.drawable.graphite,
R.drawable.sense5_full,
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(250, 180));
return imageView;
}
}
To add TextView you can create your own layout and inflate it dynamically in getView method of the adapter.
To manage the link part you can have a String array and in onItemClick method you can get the specific url using position parameter and use it as you want
-Edit-
xml you can use for the TextView part
my_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView
android:id="#+id/appIcon"
android:layout_height="60dp"
android:layout_width="60dp"
android:src="#drawable/albumstack1"
android:layout_centerHorizontal="true"
/>
<TextView
android:id="#+id/appNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/appIcon"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:textIsSelectable="false"
android:text="My Application name"
/>
</RelativeLayout>
You can inflate it in the getView method using
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = li.inflate(R.layout.my_view, null);
((TextView)v.findViewById(R.id.appNameTextView)).setText("put your text here");
((ImageView)v.findViewById(R.id.appIcon)).setImageResource(mThumbIds[position]);
}
return v;
}
For the link part you had listHttp in your question, you can use the same in
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
/**your code**/
//This is the string you need for the url, do whatever you want to do with this string
String urlForApp = listHttp.get(position);
}
}
I have a list view and each row contains two textviews and a checkbox.
I need user sets just one of checkboxes and if user sets other checkbox, previous checkbox should be cleared and second checkbox can be set.
I can generate the list but i don't know why onListItemClick() method does not work? therefore, I don't know which checkbox is set.
and my next question is, how can i redraw list after clicking checkbox by user?
my code is:
package com.Infindo.DRM;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class Infindo_PackageActivity extends ListActivity {
private final String[] titels = {"Try before buy", "Pay per play", "Pay per day", "Pay per week", "Pay per month", "Daily subscription", "Weekly subscription", "Monthly subscription"};
private final String[] descriptions = {"Free of charge", "Price: $1.00", "Price: $5.00", "Price: $10.00", "Price: $30.00", "Price: $5.00", "Price: $10.00", "Price: $30.00"};
private String[] flag = {"false", "false", "false", "false", "false", "false", "false", "false"};
private ListAdapter listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.infindo_packagepage);
listAdapter = new ListAdapter(this);
setListAdapter(listAdapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i("List Clicked:", "******");
}
public void onCheckboxClicked(View v){
int i = getSelectedItemPosition();
Log.i("item pos:", String.valueOf(i)); // every time the result is -1???
}
//*********************
// RowModel Class
//*********************
private class RowModel{
TextView title;
TextView description;
CheckBox checkbox;
}
//*********************
// ListAdapter Class
//*********************
private class ListAdapter extends ArrayAdapter<String>{
public ListAdapter(Context c) {
super(c, R.layout.infindo_listformat, titels);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RowModel holder;
View row = convertView;
if(row == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.infindo_listformat, parent, false);
holder = new RowModel();
holder.title = (TextView) row.findViewById(R.id.title);
holder.description = (TextView) row.findViewById(R.id.description);
holder.checkbox = (CheckBox) row.findViewById(R.id.checkbox);
row.setTag(holder);
} else {
holder = (RowModel) row.getTag();
}
holder.title.setText(titels[position]);
holder.description.setText(descriptions[position]);
String s = flag[position];
if(s.equalsIgnoreCase("false"))
holder.checkbox.setChecked(false);
else
holder.checkbox.setChecked(true);
return(row);
}
}
}
Update:
I have added
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
Log.i("List Redrawed:", "**notifyDataSetChanged()**");
}
into my List Adapter class and called it in
public void onCheckboxClicked(View v){
int i = getSelectedItemPosition();
Log.i("item pos:", String.valueOf(i)); // every time the result is -1???
listAdapter.notifyDataSetChanged();
}
I think the problem of redraw is solved. but I still I don't know what checkbox is clicked by the user in order to change flag array.
You can use setOnCheckedChangeListener to know which checkbox was selected. You can look at complete example of ListView with CheckBox here.
UPDATE
To make your onListItemClick() work you need to write android:focusable="false" for other items of the ListView, its because of the focus of other views ListView's onListItemClick() is not peforming as it should be performing.
Checkout this answer, why Android custom ListView unable to click on items
You probably need to handle the click from the checkbox itself and not just the listview.
So this is a bit complicated situation, so I will try to explain what is going on as best I can. I have a sqlite db which populates a listview. Each item in the listview contains the name of the item, along with two buttons. I want these two buttons to be able to use the sqlite db row id of the item they're contained in order to execute their purpose. So I need to get the id of the item, but I don't think using onListItemClick(ListView l, View v, int position, long id) will work for me, becuase I'm not clicking the entire item, rather, buttons within it. If I'm misunderstanding this point, please let me know. In order for the buttons to be clicked, I've created a class which extends SimpleCursorAdapter, which correctly handles clicks. Here are the two classes in question. First, the listactivity, and second, the custom listadapter.
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
public class FriendRequestList extends ListActivity implements OnClickListener {
private Button m_closeButton;
private TagDBAdapter mDbAdapter;
private Cursor mCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbAdapter = new TagDBAdapter(this);
mDbAdapter.open();
this.initLayout();
fillData();
}
private void initLayout() {
setContentView(R.layout.request_list);
m_closeButton = (Button)findViewById(R.id.request_window_close_button);
m_closeButton.setOnClickListener(this);
}
private void fillData() {
SharedPreferences prefs = this.getSharedPreferences("Prefs", MODE_WORLD_READABLE);
String username = prefs.getString("keyUsername", "");
RestClient.getRequests(username, this);
mCursor = mDbAdapter.fetchAllRequests();
startManagingCursor(mCursor);
String[] from = new String[] {TagDBAdapter.KEY_NAME};
int[] to = new int[] {R.id.requester};
SimpleCursorAdapter requests = new FriendRequestListAdapter(this, R.layout.request_view, mCursor, from, to);
this.setListAdapter(requests);
}
public String getRequester() {
return null;
}
#Override
public void onClick(View v) {
SharedPreferences prefs = this.getSharedPreferences("Prefs", MODE_WORLD_READABLE);
String username = prefs.getString("keyUsername", "");
RestClient.getUpdates(username, this);
Intent intent = new Intent(this, MainMenu.class);
this.startActivity(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
mDbAdapter.close();
}
}
And the adapter class:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
public class FriendRequestListAdapter extends SimpleCursorAdapter implements OnClickListener {
private Context mContext;
public FriendRequestListAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Button confirm = (Button)view.findViewById(R.id.confirm_request);
confirm.setOnClickListener(this);
Button deny = (Button)view.findViewById(R.id.deny_request);
deny.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
SharedPreferences prefs = mContext.getSharedPreferences("Prefs", Activity.MODE_WORLD_READABLE);
String username = prefs.getString("keyUsername", "");
//want to get the id here so i can do stuff with the buttons
switch(v.getId()) {
case R.id.confirm_request :
String confirmState = "2";
//these buttons both work
break;
case R.id.deny_request :
String denyState = "3";
//these buttons both work
Log.e("TESTING", "deny");
break;
}
}
}
I hope I've made my question clear enough. To summarize, I don't know how I would get the rowId of the item a pair of buttons is nested in, because I'm not ever using the onListItemClick method, which is, as far as I'm aware, the way one would normally get the id of the item. Thank you for reading and thank you for your answers. Please let me know if there is any clarifications I can make.
Create your a class by implements OnClickListener
class myCustomClass implements OnClickListener {
int rowid;
public myCustomClass(int rowid){
this.rowid=rowid;
}
#Override
public void onClick(View v) {
//do you code in 'rowid' will have the current row position
}
}
So in your
getView
function you can set listener like this
//your other codes
confirm.setOnClickListener(new myCustomClass(position));
//your other codes
deny.setOnClickListener(new myCustomClass(position));
//your other codes
Hope this give you an idea.
you maybe can do like this,in your custom adapter the getView method
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
//you can set view's tag here
//and you should do the reflect on your position to your rowid
view.setTag(customMethodForGetId(position));
//end
Button confirm = (Button)view.findViewById(R.id.confirm_request);
confirm.setOnClickListener(this);
Button deny = (Button)view.findViewById(R.id.deny_request);
deny.setOnClickListener(this);
return view;
}
and in your click event you can get the id by view.getTag();
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Button confirm = (Button)view.findViewById(R.id.confirm_request);
confirm.setOnClickListener(this);
view.setTag(position);
Button deny = (Button)view.findViewById(R.id.deny_request);
deny.setOnClickListener(this);
view.setTag(position);
return view;
}
#Override
public void onClick(View v) {
// get the position here
Integer position = (Integer)v.getTag();
switch(v.getId()) {
case R.id.confirm_request :
break;
case R.id.deny_request :
String denyState = "3";
break;
}
}