hi i want to put a cursor content in a list view is there any specific way to do it ?
i researched online nothing specific
i get this error when excuting
public class AfficherToousLesMembre extends AppCompatActivity {
String nom,prenom,email;
int numero;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afficher_toous_les_membre);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BaseDeDonee bdd = new BaseDeDonee(this);//database
Cursor c =bdd.GETallMem();//function returns all the data from table person
ArrayAdapter<String> mp = new ArrayAdapter<String>(this,R.layout.display_member_row);
c.moveToFirst();
listView=(ListView)findViewById(R.id.listView);
while(c.moveToNext()){
nom= c.getString(c.getColumnIndex("nom"));
prenom=c.getString(c.getColumnIndex("prenom"));
email=c.getString(c.getColumnIndex("profile"));
numero=c.getInt(c.getColumnIndex("numero_tel"));
String f=Integer.toBinaryString(numero);
mp.add(nom);
mp.add(prenom);
mp.add(email);
mp.add(f);
}
listView.setAdapter(mp);
}
}
and the layout is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#76ba7e"
android:layout_height="75dp">
<TextView
android:layout_width="70dp"
android:layout_height="match_parent"
android:id="#+id/nom_id"
android:layout_alignParentLeft="true"
android:text="nom"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="80dp"
android:layout_height="match_parent"
android:id="#+id/prenom_id"
android:layout_toRightOf="#+id/nom_id"
android:text="Prenom"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="70dp"
android:layout_height="match_parent"
android:id="#+id/email_id"
android:layout_toRightOf="#+id/prenom_id"
android:text="Email"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="#+id/numero_tele_id"
android:layout_toRightOf="#+id/email_id"
android:text="Numero telephone"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
please help i spend the hole day trayin to figure it out
Here your adapter need to change like this
ArrayAdapter(Context context, int resource, T[] objects).
this is the basic constructor for ArrayAdapter you can use this below way.
(1) If you use Default layout for single value in ListItem than make it like
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
where items is a array of object which you want to display in ListView
(2) If you want to display single item in your custom layout for ListItem than make it like
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this,
R.layout.rowlayout, R.id.label, values);
where R.id.label is a resource in which you want to display values
(3) Make your own Adapter to display bulk data in your ListItem
for this refer http://www.vogella.com/tutorials/AndroidListView/article.html
public class CustomListAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomListAdapter (Context mContext, String[] NameList, int[] Images) {
// TODO Auto-generated constructor stub
result=NameList;
context=mContext;
imageId=Images;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.row_list_item, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
and used like this
ListView yourListView = (ListView) findViewById(R.id.itemListView);
CustomListAdapter customAdapter = new CustomListAdapter(this,String Array of NameList, int Array of Images);
yourListView.setAdapter(customAdapter);
Mainactivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
listview_detail.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
MainActivity.Java
//getting all user data from database
UserMst sql_userMst = new UserMst(context);
sql_usermst.open();
Cursor cursor = sql_userMst.getAllUserData();
//binding cursor to listview
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(new TodoCursorAdapter(context,cursor));
public class TodoCursorAdapter extends CursorAdapter {
public TodoCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.listview_detail, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView label = (TextView) view.findViewById(R.id.label);
// Extract properties from cursor
String username= cursor.getString(cursor.getColumnIndexOrThrow("UserName"));
// Populate fields with extracted properties
label .setText(username);
}
}
use this url for reference listview with cursor
Related
I have a dynamically created list. It's fragment-layout is as follows:
<ListView
android:id="#+id/colorsList"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
When I add a row to the listview, I want an "X" mark to appear at the end of the row so that when the user clicks on the "X", the row gets deleted.
Not sure, if its relevant but, the way I am adding and removing rows to the listview is as follows.
Logic to add a row tot he listView:
#BindView(R.id.understood_languages_list)
View mColorsList;
*********
*********
ListView listFavoriteColors;
listFavoriteColors = (ListView) mColorsList;
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, getColorsList());
listFavoriteColors.setAdapter(arrayAdapter);
Logic to remove a row from the ListView.
listFavoriteColors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
initializeView();
arrayAdapter.remove(((TextView)view).getText().toString());
}
});
Any helpful suggestions on how this can be achieved is much appreciated.
User Custom Adapter with custom Layout to attach delete button to each item in listview
try this code :
CustomAdapter
public class ListAdapter extends ArrayAdapter<String> {
private int resourceLayout;
private Context mContext;
ListInterFace interface;
public ListAdapter(Context context, int resource, List<String>
items,ListInterFace interface) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
this.interface=interface;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}
String value= getItem(position);
if (value!= null) {
TextView tt1 = (TextView) v.findViewById(R.id.dummytext);
Button cancel_click=v.findViewById(R.id.cancel_click);
if (tt1 != null) {
tt1.setText(value);
}
//remove item on button click
cancel_click.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
interface.removeItem(position);
}
})
}
return v;
}
}
R.layout.itemlistrow defines the row of the ListView.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dummytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy"
android:textColor="#android:color/black"
android:textSize="18sp"
android:padding="5dp"/>
<ImageView
android:id="#+id/cancel_click"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#mipmap/cancel"
android:layout_alignParentRight="true"
android:layout_margin="5dp"/>
</RelativeLayout>
</LinearLayout>
In the MainActivity define ListViewlike this,
ListView yourListView = (ListView) findViewById(R.id.itemListView);
// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, myList, new ListInterFace () {
#Override
public void removeItem( int position) {
myList.remove(position);
customAdapter .notifyDataSetChanged();
});
yourListView .setAdapter(customAdapter);
InterFace
public interface ListInterFace {
void removeItem(int position);
}
try this link to remove item from list view on button click
Remove Item From List View On Button Click
The idea is I want to display list of mp3 files from SDCARD in listview, each line is also contain a spinner with three items (share, rename and delete), I used custom arrayadapter for this purpose and I am stuck on how to add the spinner on the custom arrayadapter class
this is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:theme="#style/AppTheme"
tools:context=".MainActivity"
>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="416dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp" />
<Button
android:id="#+id/stopBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:layout_marginBottom="28dp"
android:text="Stop" />
</LinearLayout>
this is where i create the spinner
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingLeft="14dp"
>
<TextView
android:id="#+id/text1"
android:layout_width="0dp"
android:layout_height="33dp"
android:layout_weight="1"
android:gravity="center|start"
/>
<Spinner
android:id="#+id/spinner"
android:layout_width="31dp"
android:layout_height="33dp"
android:layout_gravity="right"
android:background="#drawable/download"
>
</Spinner>
</LinearLayout>
here I create the datatype
public class MyDataType {
// Name of the song
private String mSongName;
// Drawable Menu resource ID
private int mSpinner;
/** Audio resource ID for the word */
//private int mAudioResourceId;
//public MyDataType(String vName, int imageResourceId, int audioResourceId){
public MyDataType(String vName, int spinner){
mSongName = vName;
mSpinner = spinner;
//mAudioResourceId = audioResourceId;
}
public String getSongName() {
return mSongName;
}
public int getSpinner() {
return mSpinner;
}
}
here i create the custom adapter
public class SongAdapter extends ArrayAdapter<MyDataType> {
public SongAdapter(Context context, ArrayList<MyDataType> words) {
super(context, 0, words);
}
Spinner mSpinner;
ArrayAdapter<CharSequence> mAdapter;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyDataType currentSong = getItem(position);
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.song_list, parent, false);
}
TextView songTextView = (TextView)
listItemView.findViewById(R.id.text1);
songTextView.setText(currentSong.getSongName());
mSpinner = (Spinner) listItemView.findViewById(R.id.spinner);
return listItemView;
}
}
this is the main activity
public class MainActivity extends AppCompatActivity {
private static final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Xylophone/";
ArrayList<MyDataType> file_list = new ArrayList<MyDataType>();
private final ArrayList<String> songs = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = new MediaPlayer();
//updatePlayList();
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
fillList();
} else {
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
}
final SongAdapter adapter = new SongAdapter(this, file_list);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
mp.reset();
mp.setDataSource(SD_PATH + songs.get(position));
mp.prepare();
mp.start();
}catch (IOException e){
Log.v(getString(R.string.app_name),e.getMessage() );
}
}
});
Button stopPlay = (Button) findViewById(R.id.stopBtn);
stopPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.stop();
}
});
}
private void fillList() {
File file = new File(SD_PATH );
File list[] = file.listFiles();
for (int i = 0; i < list.length; i++) {
//file_list.add(list[i].getName(),);
songs.add(list[i].getName());
MyDataType myList = new MyDataType(list[i].getName(), R.id.spinner);
file_list.add(myList);
}
}
}
the string value that cotain menu items
<resources>
<string name="app_name">PlayMp3List</string>
<string-array name="spinner_data">
<item>Rename</item>
<item>Delete</item>
<item>Share</item>
</string-array>
</resources>
OK, it seems that you have almost every thing in place that you need. However, there are a few minor changes you will need to make before this is working. First, in the code where you check the permissions if permission is granted, you call fillList(). But in the Else condition, you request the permission. In the code above, you are not showing how you are handling the result of the request for permission. If the permission is granted after the request, then in that case, you must also call fillList() there as well. And, after calling fillList() there, you will also need to recreate the SongAdapter, and also redo the setAdapter on your list view.
In fillList(), you are initializing your myList item with the song title, and the ID of a spinner. You shouldn't be doing that. What you should be doing is populating the myList item with the 'value' of the spinner... and the default should probably be 0.
In your getView() method in the custom Adapter, you are getting the current item based on the position parameter and putting the song title into the textView. Then, you are getting a reference to the Spinner, but you are not doing anything with it. After getting the reference you should be doing something like mSpinner.value = currentSong.getSpinner();
What you want to do in your MyDataType class is to store the value of the spinner, not any reference to the spinner itself. You also need some sort of click event so that if the user changes the value of the spinner in the row, you can update your ArrayList with the new value. That assumes the user can change that selected spinner item, if not, then when you are creating the list, you have to figure out what value to set each song's spinner value with, which you are not doing.
Your Adapter code should look like this. Note the removal of getContext().
public class SongAdapter extends ArrayAdapter<MyDataType> {
Context mContext = null;
public SongAdapter(Context context, ArrayList<MyDataType> words) {
super(context, 0, words);
mContext = context;
}
Spinner mSpinner;
ArrayAdapter<CharSequence> mAdapter;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyDataType currentSong = getItem(position);
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(mContext.inflate(R.layout.song_list, parent, false);
}
TextView songTextView = (TextView)
listItemView.findViewById(R.id.text1);
songTextView.setText(currentSong.getSongName());
mSpinner = (Spinner) listItemView.findViewById(R.id.spinner);
mSpinner.value = currentSong.getSpinner();
return listItemView;
}
}
In your list item click method you will need to set a breakpoint to see that the path you are passing in mp.setDataSource is a valid path. It is possible that your SD_PATH needs a '/' at the end or something.
In your layout.xml file you would define your spinner like this:
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/country_arrays"
android:prompt="#string/country_prompt" />
Where the entries #array/country_arrays points to the list that you defined in Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyAndroidApp</string>
<string name="country_prompt">Choose a country</string>
<string-array name="country_arrays">
<item>Malaysia</item>
<item>United States</item>
<item>Indonesia</item>
<item>France</item>
<item>Italy</item>
<item>Singapore</item>
<item>New Zealand</item>
<item>India</item>
</string-array>
</resources>
You are missing the value in your spinner xml definition:
<Spinner
android:id="#+id/spinner"
android:layout_width="31dp"
android:layout_height="33dp"
android:layout_gravity="right"
android:background="#drawable/download"
android:entries="#array/spinner_data"
>
</Spinner>
I've seen lots of posts regarding this question but none of them guided me through a solution to my problem. I have a listview using a custom cursoradapter which every item has a checkbox in it. This checkbox is not binded to the database, because my intention is to use it for deletion. Once delete button is clicked, all items with checkboxes checked should be deleted from view and database. I implemented the following logic, but turns out the method <my listview instance>.getCheckedItemPositions() always returns a SparseBooleanArray empty. Can anyone tell me what I am doing wrong? I am not sure if this is the best approach anyway, so any other solution or ideas are welcome.
This is my CursorAdapter
public class ExpenseCursorAdapter extends CursorAdapter {
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
Context context;
private DatabaseHelper db;
public ExpenseCursorAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.expense_single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewParticipantId = (TextView) view.findViewById(R.id.tv_expense_participant);
textViewParticipantId.setText(cursor.getString(cursor.getColumnIndex("name")));
TextView textViewExpenseDescription = (TextView) view.findViewById(R.id.tv_expense_description);
textViewExpenseDescription.setText(cursor.getString(cursor.getColumnIndex("description")));
TextView textViewExpenseAmount = (TextView) view.findViewById(R.id.tv_expense_amount);
textViewExpenseAmount.setText(formatter.format(Double.valueOf(cursor.getDouble(cursor.getColumnIndex("amount")))));
}
}
This is my item layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="1,2,3" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="10" >
<CheckBox
android:id="#+id/cb_expense_row"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:button="#drawable/selector_check"
android:focusable="false"
android:padding="2dip"
android:weightSum="1"/>
<TextView
android:id="#+id/tv_expense_participant"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:weightSum="3"
android:gravity="left"/>
<TextView
android:id="#+id/tv_expense_description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:weightSum="3"
android:gravity="left"/>
<TextView
android:id="#+id/tv_expense_amount"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:weightSum="3"
android:gravity="left" />
</TableRow>
And this is the activity with the logic I am using on delete button --removeExpense():
private static final String TAG = ExpenseActivity.class.getSimpleName();
private ListView listView;
private ExpenseCursorAdapter customAdapter;
private DatabaseHelper databaseHelper;
private long eventId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expense);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
eventId = getIntent().getLongExtra("tag_event_id", -1);
databaseHelper = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.expense_list_data);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position+" - ID: "+id);
}
});
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new ExpenseCursorAdapter(ExpenseActivity.this, databaseHelper.getAllExpensesByEventCursor(eventId));
listView.setAdapter(customAdapter);
}
});
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
...
private void removeExpenses() {
Log.d(TAG, "Remove Expense button clicked on");
DatabaseHelper db = new DatabaseHelper(this);
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
int itemCount = listView.getCount();
for (int i = itemCount - 1; i >=0; i--) {
if (checkedItemPositions.valueAt(i)) {
//db.deleteExpense(listView.getItemIdAtPosition(checkedItemPositions.keyAt(i)));
db.deleteExpense(listView.getItemIdAtPosition(i));
}
customAdapter.notifyDataSetChanged();
}
checkedItemPositions.clear();
listView.setAdapter(customAdapter);
listView.clearChoices();
if (db != null){
db.close();
}
}
I have a custom list adapter that populates a listview.
I am trying to get each item in the listview to be clickable. When clicked, I want the app to load another activity and populate it with the proper data. The data comes from a java list of listing.java.
I can't seem to get it to respond to clicks, here is what I've tried so far:
//this is in the onCreate method
final ListView listview = (ListView) findViewById(R.id.listview);
listingsAdapter = new ListingsAdapter(this, mylistings);
listview.setAdapter(listingsAdapter);
here is my first attempt (this was just to get toast working, but it didn't work)
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view,int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG).show();
};
});
I have also tried this:
listview.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(HomeScreenActivity.this, DetailedViewActivity.class);
startActivity(i);
};
});
Help would be appreciated. Let me know if I should post my adapter as well!
Here is the adaptor:
public class ListingsAdapter extends BaseAdapter{
List<Listing> listings;
Context context;
LayoutInflater inflater;
public ListingsAdapter(Context context, List<Listing> listings){
this.context = context;
this.listings = listings;
inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public boolean isEnabled(int position)
{
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View _localView = convertView;
if (_localView == null){
_localView = inflater.inflate(R.layout.main_cell, parent, false);
}
TextView text1 = (TextView) _localView.findViewById(R.id.firstline);
TextView text2 = (TextView) _localView.findViewById(R.id.secondLine);;
Listing listing = listings.get(position);
text1.setText(listing.getTitle());
text2.setText(listing.getAddress());
return _localView;
}
#Override
public int getCount(){
// TODO Auto-generated method stub
return listings.size();
}
#Override
public Object getItem(int arg0){
return listings.get(arg0);
}
#Override
public long getItemId(int arg0){
// TODO Auto-generated method stub
return arg0;
}
}
this is the main_cell.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
<TextView
android:id="#+id/firstline"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/secondLine"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="16sp"/>
</RelativeLayout>
Right, so I am recovering from a severe hangover and I just remembered that I promised to elaborate on the link I posted - disregard the link!
You should add the following piece of code to your ListingsAdapter:
#Override
public boolean isEnabled(int position)
{
return true;
}
And you should edit the RelativeLayout in your main_cell.xml from
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43"
android:longClickable="true">
to
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43">
This works, I have tested it.
try to initialize local instance of View:
#Override
public View getView(int position, View convertView, ViewGroup parent){
View _localView = convertView;
if (_localView == null){
_localView = inflater.inflate(R.layout.main_cell, parent, false);
}
TextView text1 = (TextView) _localView.findViewById(R.id.firstline);
TextView text2 = (TextView) _localView.findViewById(R.id.secondLine);;
Listing listing = listings.get(position);
text1.setText(listing.getTitle());
text2.setText(listing.getAddress());
return _localView;
}
UPD:
Also modify other necessary methods in your adapter class, because you need to get id of an item clicked for using it in onItemClick method:
#Override
public Object getItem(int arg0){
// TODO Auto-generated method stub
listings.get(arg0);
}
#Override
public long getItemId(int arg0){
// TODO Auto-generated method stub
return arg0;
}
as an example. Hope this will help you.
I'm trying to show a ListView from a PopupWindow. but when I'm try to call ListView's setOnItemClickListener nothing to haapen. Here It Java file
PopupWindowActivity.java
public class PopupWindowActivity extends Activity {
String[] data = { "DATA 1", "DATA 2", "DATA 3", "DATA 4", "DATA 5", "DATA 6" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.main, null);
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ListView listView = (ListView) popupView.findViewById(R.id.listView1);
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,data));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
System.out.println("Item Clicked");
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(btnOpenPopup, 20, -5);
}
});
}
}
Here it is first xml file
a.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/openpopup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Open Popup Window" />
</LinearLayout>
Here it inflate xml file
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/recording"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="30sp"
android:layout_marginLeft="30sp"
android:layout_marginRight="30sp"
android:layout_marginTop="100sp" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000" >
</ListView>
</RelativeLayout>
</LinearLayout>
What am I doing wrong?
Thanks
Just one minor change in your code and BOOOM your code will listen to you list click event
final PopupWindow popupWindow = new PopupWindow(popupView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
You forget to mention focusable setting true in PopupWindow constructor.
had the same problem, but in my case setFocusble(false) was required (and using ListPopupWindow was not a solution in my case as a lot of stuff in the project already used base PopupWindow's functionality including extending).
If someone in the same situation there is a kind of workaround based on bug discusson here (post #9)
The main idea is that ListView's hierarchy is still receives touch events so we can manually trigger onItemClick().
However this approach is not 100% identical to real ListView's touch handling (like there is no glow of selection while tapping a row) this done pretty well for me for the moment.
If someone has more precise solution of this problem, please share.
So, here is complete Adapter's code which can be used with ListView inside PopupWindow which is setFocusable(false):
private class CustomAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
private ListView mOwningListView;
public CustomAdapter(Context context, List<String> objects, ListView listView) {
super(context, android.R.layout.simple_list_item_1, objects);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mOwningListView = listView;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.font_pick_row, null);
}
// this is the key point of workaround
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* as every row is still receiving their touches
* we can use this to manually trigger onItemClick
* since it doesn't firing in popupWindow.setFocusable(false)
*/
mOwningListView.getOnItemClickListener().onItemClick(mOwningListView, v, position, getItemId(position));
}
});
//... other stuff
return convertView;
}
}
May this help you
.
Declare listview and list onClickListener outside the button ClickListener.