Why isn't my listview selectable? - java

I have a custom CursorAdapter and it looks like :
public class LabelAdapter extends CursorAdapter {
Context con;
LayoutInflater mFactory;
public AlarmTimeAdapter(Context context, Cursor c) {
super(context, c);
con = context;
mFactory = LayoutInflater.from(con);
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
final String label2 = cursor.getString(AlarmData.ALARM_TITLE_INDEX);
..code to fill in the textview with whats in the cursor
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View ret = mFactory.inflate(R.layout.item_lv, parent, false);
return ret;
}
}
my item_lv looks like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:focusable="true"
>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="14dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
When I call :
ListView lv = (ListView)findViewById(R.id.listview); //Listview is in the main.xml file
lv.setAdapter(new LabelAdapter(this, mCursor);
lv.setFocusable(true);
The items in the listview aren't selectable.. does anyone know whats wrong? I've set the items focusable, but they aren't able to be clicked. Help! Thanks!

Set onItemClickListener to your listView-
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,
long arg3) {
});

Remove android:focusable="true" from RelativeLayout for your item.

I believe the answer is really simple. Set the textview in the .xml should be
Android:Clickable = "True"
Reason for this is that if you are putting this as rows they have to be clickable in order to recognize click events.

Related

How can I attach a delete button (x) to each member of a dynamically created ListView?

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

Android: Why is onItemClick for my ListView using ArrayAdapter not working?

I have a ListView made up of a LinearLayout and some elements within. It's driven by a custom Adapter that extends ArrayAdapter>. For some reason it's not getting called when I click on of of the displayed items. Nothing happens in logcat. No error, no Log, nothing.
I've read a number of similar questions, and tried to implement the solutions, but that doesn't seem to be my issue. I tried onItemClickListener not firing on custom ArrayAdapter and Listview onitemclick listener is not working and OnItemClick not responding to clicks
Here's my activity code:
ratingAdapter = new RatingAdapter(this, RatingRecord);
ratingListView = (ListView) findViewById(R.id.ratingsListView);
ratingListView.setAdapter(ratingAdapter);
ratingListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("Ratings update", "Clicked button for " + RatingRecord.get(i).get(1));
RateRestaurant(RatingRecord.get(i));
}
});
Here's my item xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:clickable="true"
android:id="#+id/ratings_row"
style="#android:style/Widget.Button"
android:descendantFocusability="blocksDescendants"
android:focusable="true">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_weight="2"
android:id="#+id/rating_name"
android:focusable="false"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:adjustViewBounds="true"
android:paddingRight="5dp"
android:id="#+id/rating_icon"
android:focusable="false"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_weight="1"
android:id="#+id/rating_date"
android:gravity="center_horizontal"
android:focusable="false"/>
</LinearLayout>
Here's the ListView layout from the main activity:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:id="#+id/ratingsListView"/>
Here's the meat of the adapter RatingAdapter:
public RatingAdapter(Context context, ArrayList<ArrayList<String>> inValues) {
super(context, R.layout.ratings_row, inValues);
this.context = context;
ratingList = CsvUtil.fromCsvTable(context.getString(R.string.Ratings_OptionsList));
}
private ViewHolder(View c, Integer n, Integer i, Integer d) {
NameView = (TextView)c.findViewById(n);
IconView = (ImageView)c.findViewById(i);
DateView = (TextView)c.findViewById(d);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ArrayList<String> record = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder vh;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.ratings_row, parent, false);
vh = new ViewHolder(convertView,R.id.rating_name,R.id.rating_icon,R.id.rating_date);
convertView.setTag(vh);
} else {
vh = (ViewHolder)convertView.getTag();
}
// Lots of data calculation and populating ViewHolder elements
return convertView;
}
Nothing happens. Like I said, no log or event or error. What have I done wrong?
set on click on your convertview in adapter getView() method.
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Ratings update", "Clicked button for " + RatingRecord.get(i).get(1));
RateRestaurant(RatingRecord.get(i));
}
}
Answer provided by Haresh in the comments.
"please try to remove this line style="#android:style/Widget.Button" from your list item layout"
I used the style Widget.Button to give me the look of a button though the ListView already provided the click through functionality. However the style did more than change the look. It also overrode the clicking function. To get the effect I wanted without the side effects, I just set the background using:
android:background="#android:drawable/btn_default"

How do I delete items from a cursoradapter listview?

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

change the spinner title bar style

How can i change the spinner title bar style.
I wish to change the title bar for the following items:
icon
title textsize,textColor and
background color
How can i do this?
please help me...i have searched google and more sites.am not getting any solution for this.so please let me know its possible.if possible means how can i develop this????please explain me.
EDIT:
This is my code:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row, R.id.country, list);
spinner.setPrompt("Choose a Status");
// spinner.setTextColor("#FF0000");
spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
You have to create CustomSpinner,
To do so try this following way, it works well for me
Step 1: Create Custom Spinner Class
class CustomSpinnerAdapter extends CursorAdapter {
LayoutInflater mInflater;
private int cocktailname;
CustomSpinnerAdapter(Context context, Cursor cursor)
{
super(context, cursor);
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cocktailname = cursor.getColumnIndex(YourDatabase.CK_NAME);
}
#Override
public View newDropDownView (Context context, Cursor cursor, ViewGroup parent)
{
return mInflater.inflate(R.layout.dropdownspinnertext, parent, false);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
return mInflater.inflate(R.layout.spinnertext, parent, false);
}
#Override
public void bindView(View row, Context context, Cursor cursor)
{
//Setting the Value here
TextView paymentname = (TextView) row.findViewById(R.id.text1);
paymentname.setTypeface(textFont);
String cocktail = cursor.getString(cocktailname);
paymentname.setText(cocktail);
}
}
Step 2 : Call this Adapter
CustomSpinnerAdapter custom_spinneradapter = new CustomSpinnerAdapter(this,youcursor);
spnListCocktails.setAdapter(custom_spinneradapter);
spnListCocktails.setOnItemSelectedListener(this);
Xml for dropdownspinnertext
I am using Checked Dropdown Spinner
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textColor="#FFFFFF"
android:textSize="18sp"
android:background="#drawable/background_image"
/>
For spinnertext.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:gravity="center"
android:padding="4dip"
android:layout_marginLeft="10dip"
android:textSize="20sp"/>
Hope it helps
Using Java (Code):
spinner.setPrompt("Title")
OR
From XML:
android:prompt="#string/spinner_title
See this to change style

Android ListView's setOnItemClickListener from PopupWindow not called

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.

Categories

Resources