ListView not clickable even with descendantFocusability - android

I'm trying to implement a ContextMenu, but by doing so I checked that my listview was not clickable.
I went over different threads based on this subject and tried everything proposed android:focusable="false" android:focusableInTouchMode="false"
even
descendantFocusability="blocksDescendants"
but still not working
Here is my main xml :
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".HomePage">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnAddTask"
android:id="#+id/btnAddTask"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="goToAddTask" />
<ListView
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listViewTasks"
android:layout_alignParentStart="true"
android:layout_above="#+id/btnAddTask"
android:layout_below="#+id/txtTaskList"
android:longClickable="true"
android:clickable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/txtTaskList"
android:id="#+id/txtTaskList"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Here is my list_item xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:layout_alignParentStart="true">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnDelete"
android:src="#drawable/no_cross"
android:onClick="goToDeleteTask"
android:layout_gravity="center_vertical"
android:contentDescription="Delete button" />
<LinearLayout
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical"
android:clickable="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/txtTaskListName"
android:id="#+id/txtTaskListName"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/txtTaskListDate"
android:id="#+id/txtTaskListDate"
android:layout_below="#+id/txtTaskListName"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/txtTaskListTime"
android:id="#+id/txtTaskListTime"
android:layout_marginLeft="10dp"
android:layout_below="#+id/txtTaskListName"
android:layout_toEndOf="#+id/txtTaskListDate"
android:layout_marginStart="24dp" />
</LinearLayout>
</LinearLayout>
And finally my java code:
public class HomePage extends ActionBarActivity {
final Context context = this;
private static final int EDIT = 0, DELETE = 1;
DatabaseHandler dbHandler;
ListView taskListView;
ArrayAdapter<Task> taskAdapter;
int longClickedItemIndex;
List<Task> Tasks = new ArrayList<Task>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
dbHandler = new DatabaseHandler(getApplicationContext());
taskListView = (ListView) findViewById(R.id.listViewTasks);
// The following piece of code allows to empty database before testing when reinstalling the app for test.
//getApplicationContext().deleteDatabase("myTasks");
registerForContextMenu(taskListView);
taskListView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
taskListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
});
if (dbHandler.getTasksCount() != 0)
Tasks.addAll(dbHandler.getAllTasks());
populateTasksList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class TaskListAdapter extends ArrayAdapter<Task> {
public TaskListAdapter(){
super(HomePage.this, R.layout.tasklist_item, Tasks);
}
#Override
public View getView(int position, View view, ViewGroup parent){
if (view == null) {
view = getLayoutInflater().inflate(R.layout.tasklist_item, parent, false);
}
Task currentTask = Tasks.get(position);
TextView taskListName = (TextView) view.findViewById(R.id.txtTaskListName);
taskListName.setText(currentTask.getTitle());
TextView taskListDate = (TextView) view.findViewById(R.id.txtTaskListDate);
taskListDate.setText(currentTask.getDate());
TextView taskListTime = (TextView) view.findViewById(R.id.txtTaskListTime);
taskListTime.setText(currentTask.getTime());
/*ImageButton deleteButton = (ImageButton) view.findViewById(R.id.btnDelete);
//deleteButton.setTag(currentTask.getId());
deleteButton.setTag(R.id.taskId,currentTask.getId());
deleteButton.setTag(R.id.position,position);*/
return view;
}
}
private void populateTasksList() {
taskAdapter = new TaskListAdapter();
taskListView.setAdapter(taskAdapter);
}
public void goToAddTask(View view){
Intent intent = new Intent(this, AddTask.class);
startActivity(intent);
}
public void goToDeleteTask(final View view){
AlertDialog alertDialog = new AlertDialog.Builder(context)
// Set Dialog Icon
.setIcon(R.drawable.ic_bullet_key_permission)
// Set Dialog Title
.setTitle(R.string.removeAlert)
// Set Dialog Message
.setMessage(R.string.deleteMessage)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ImageButton deleteButton = (ImageButton) view.findViewById(R.id.btnDelete);
// Retrieving the task to delete
int taskId = (int) deleteButton.getTag(R.id.taskId);
Task taskToDelete = dbHandler.getTask(taskId);
// Removing the task from the database and from the calendar
dbHandler.deleteTask(taskToDelete, context);
// Removing the task from the listView
TaskListAdapter tAdapter = (TaskListAdapter)taskListView.getAdapter();
int position = (int)deleteButton.getTag(R.id.position);
tAdapter.remove(tAdapter.getItem(position));
tAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), R.string.removedTask, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
}
})
.create();
alertDialog.show();
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.edit_pencil_icon);
menu.setHeaderTitle(R.string.contextMenu_title);
menu.add(menu.NONE, EDIT, menu.NONE, R.string.contextMenu_edit);
menu.add(menu.NONE, DELETE, menu.NONE, R.string.contextMenu_delete);
}
public boolean onContextItemSelected (MenuItem item) {
switch (item.getItemId()) {
case EDIT:
// TODO : Implement editing a task
break;
case DELETE:
deleteTask();
//TODO : to be tested
/*
dbHandler.deleteTask(Tasks.get(longClickedItemIndex);
Tasks.remove(longClickedItemIndex);
taskAdapter.notifyDataSetChanged();
*/
break;
}
return super.onContextItemSelected(item);
}
public void deleteTask(){
AlertDialog alertDialog = new AlertDialog.Builder(context)
// Set Dialog Icon
.setIcon(R.drawable.ic_bullet_key_permission)
// Set Dialog Title
.setTitle(R.string.removeAlert)
// Set Dialog Message
.setMessage(R.string.deleteMessage)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ImageButton deleteButton = (ImageButton) findViewById(R.id.btnDelete);
// Retrieving the task to delete
int taskId = (int) deleteButton.getTag(R.id.taskId);
Task taskToDelete = dbHandler.getTask(taskId);
// Removing the task from the database and from the calendar
dbHandler.deleteTask(taskToDelete, context);
// Removing the task from the listView
TaskListAdapter tAdapter = (TaskListAdapter) taskListView.getAdapter();
int position = (int) deleteButton.getTag(R.id.position);
tAdapter.remove(tAdapter.getItem(position));
tAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), R.string.removedTask, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
alertDialog.show();
}
}
(2 delete functions, cause of my test I'm currently performing).

I finally tried several things and find my solution (for whom it could be usefull).
First of all I had to remove all the things related to "clickable" attribute from all my xml
Then, if you check my list item xml, I have 2 layouts (2 linear one, don't know if this could be different with Relative, did not test this).
What I did is to remove the second one, and modify the core LinearLayout to Relative Layout (to display my elements as I want).
Then I launched again my app and it's perfectly working.

Related

How do I pass the index of an item when a button is clicked from a listview?

So I'm planning on creating a simple 'no-db' todo app
I've been able to display and add items to my list.
Now I'm trying to delete by passing the index of the clicked item. The problem is that I don't know how to pass parameters. Any help would be greatly appreciated!
Here's my code
public class MainActivity extends AppCompatActivity {
List<String> notesList;
Toolbar toolbar;
ListView listNotes;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.WHITE);
notesList = new ArrayList<String>();
// notesList.add("1");
listNotes = findViewById(R.id.list_notes);
delete = findViewById(R.id.btn_delete);
loadNotesList();
}
private void loadNotesList() {
if(mAdapter == null){
mAdapter = new ArrayAdapter<String>(this,R.layout.note_item,R.id.note_title, notesList);
listNotes.setAdapter(mAdapter);
}
else {
mAdapter.clear();
mAdapter.addAll(notesList);
mAdapter.notifyDataSetChanged();
}
}
private void displayToast() {
// notesList.add("test");
Log.d("list", notesList.toString());
Toast.makeText(getApplicationContext(), notesList.toString(),
Toast.LENGTH_LONG).show();
}
private void deleteNote(View view){
View parent = (View)view.getParent();
TextView noteTitleTextView = (TextView)findViewById(R.id.note_title);
String noteTitle = String.valueOf(noteTitleTextView.getText());
Toast.makeText(getApplicationContext(), noteTitleTextView.toString(),
Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
notesList = new ArrayList<String>();
//notesList.add("tset vissew");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_add) {
displayToast();
final EditText noteEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add a new note")
.setMessage("What's on your mind?")
.setView(noteEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String note = String.valueOf(noteEditText.getText());
notesList.add(note);
loadNotesList();
displayToast();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
//loadNotesList();
//displayToast();
}
return super.onOptionsItemSelected(item);
}
}
My layout for the list item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<TextView
android:id="#+id/note_title"
android:text="Example"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:gravity="center"/>
<Button
android:id="#+id/btn_delete"
android:text="Delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
The code loooks really ugly, I'm sorry for that.
Add OnItemClickListener for your ListView
listNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//here position is index of your list's item
}
});

How do I replace my popupmenu code with ListPopupWindow?

Currently , I am programatically creating a popupmenu which displays a list of floors and a title. However, changing the background color of just the title and adding a close button to title is turning out to be a nightmare.
I want to replace this popupmenu with a list popup window so I can add an XML file with background attribute for the title with a black color as the background and a close button on the right and white background for items in the menu. Is there a way I can achieve this with list popup window? Here's my code for that:
private void floorMenu(ImageView btnFloorMenu){
MapData data = new MapDao(MyPlugin.mapId);
final List<Floor> flList = dao.getFloors();
// set popupMenu
final PopupMenu floorsPm = new PopupMenu(MapViewActivity.this,btnFloorMenu);
MenuItem titleItem = floorsPm.getMenu().add(Menu.NONE, Menu.NONE, Menu.NONE, "Floors");
int i = 1;
for(Floor fl : flList)
{
floorsPm.getMenu().add(Menu.NONE, i,i, fl.getName());
if(i>3)
break;
i++;
}
// add popup listener
floorsPm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
// onClick
#Override
public boolean onMenuItemClick(MenuItem item){
// get floorname
int flOrder = item.getOrder();
if(flOrder == Menu.NONE )
return true;
flOrder--;
final String floorId = flList.get(flOrder).getMapId();
// set camera to floor
runOnUiThread(new Runnable() {
#Override
public void run() {
floorsPm.dismiss();
mapFragment.getMapManager().setCameraLayer(floorId, false);
Log.d(TAG, "post cameraLayer set");
changedSteps = true;
pauseNav();
}
});
return true;
}
});
floorsPm.show();
}
Here is my example to create show a ListPopupWindow
First, create layout item_list_popup_window for each item of ListPopupWindow
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e4e4e4"
android:paddingTop="1dp"
android:orientation="horizontal">
<TextView
android:id="#+id/text_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" />
<Button
android:id="#+id/button_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
</LinearLayout>
Second, create an Adapter for your ListPopupWindow like
public class ListPopupWindowAdapter extends BaseAdapter{
private Activity mActivity;
private List<String> mDataSource = new ArrayList<>();
private LayoutInflater layoutInflater;
private OnClickDeleteButtonListener clickDeleteButtonListener;
ListPopupWindowAdapter(Activity activity, List<String> dataSource, #NonNull OnClickDeleteButtonListener clickDeleteButtonListener){
this.mActivity = activity;
this.mDataSource = dataSource;
layoutInflater = mActivity.getLayoutInflater();
this.clickDeleteButtonListener = clickDeleteButtonListener;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public String getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.item_list_popup_window, null);
holder.tvTitle = (TextView) convertView.findViewById(R.id.text_title);
holder.btnDelete = (Button) convertView.findViewById(R.id.button_delete);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
// bind data
holder.tvTitle.setText(getItem(position));
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickDeleteButtonListener.onClickDeleteButton(position);
}
});
return convertView;
}
public class ViewHolder{
private TextView tvTitle;
private Button btnDelete;
}
// interface to return callback to activity
public interface OnClickDeleteButtonListener{
void onClickDeleteButton(int position);
}
}
Third, You create a function for create and show ListPopupWindow
private void showListPopupWindow(View anchorView) {
final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
listPopupWindow.setWidth(600);
List<String> sampleData = new ArrayList<>();
sampleData.add("A");
sampleData.add("B");
sampleData.add("CCCCCCCCCCCCCC");
sampleData.add("D");
sampleData.add("EEEEEEEEE");
listPopupWindow.setAnchorView(anchorView);
ListPopupWindowAdapter listPopupWindowAdapter = new ListPopupWindowAdapter(this, sampleData, new ListPopupWindowAdapter.OnClickDeleteButtonListener() {
#Override
public void onClickDeleteButton(int position) {
Toast.makeText(MainActivity.this, "Click delete " + position, Toast.LENGTH_SHORT).show();
listPopupWindow.dismiss();
}
});
listPopupWindow.setAdapter(listPopupWindowAdapter);
listPopupWindow.show();
}
Finally, you can show the ListPopupWindow by
showListPopupWindow(v);
for example, if you want to show it when click button
anyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showListPopupWindow(v);
}
});
Full Demo is here
Please Try this code, Maybe you wont like this
private void floorMenu(ImageView btnFloorMenu){
final Dialog customDialog = new Dialog(this);
customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
customDialog.setContentView(R.layout.item_dialog_coustom_design);
TextView clickItem = (TextView)customDialog.findViewById(R.id.item_click);
TextView clickItem1 = (TextView)customDialog.findViewById(R.id.item_click1);
TextView clickItem2 = (TextView)customDialog.findViewById(R.id.item_click2);
Button btnClose = (Button)customDialog.findViewById(R.id.btn_close);
clickItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
clickItem1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
clickItem2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
// wright your Button Action
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
}
});
customDialog.show();
}
Create Linearlayout layout_width="280dp" layout_height="wrap_content"
android:orientation="vertical" file name item_dialog_coustom_design.xml then put this code
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Title"
android:background="#000"
android:textColor="#fff"
android:padding="12dp"
android:textSize="20sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click1"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:padding="10dp"
android:text="Your Item"
android:id="#+id/item_click2"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:background="#fff"
android:gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_close"
android:text="Close"/>
</LinearLayout>

Spinner value disappear after layout visibility is changed + specific flows

I have a custom list view with layout contain two layouts, called upper and bottom.
upper layout contain spinner, set and remove buttons.
bottom layout contain text view and back button.
By default bottom layout is in GONE state and when the user clicks on set button upper layout is GONE and bottom is VISIBLE (clicking on back button in bottom layout will return upper bottom back).
my problem is spinner value is disappear after specific flows:
Flow 1:
Add two items
Click on SET button on the first item
Remove the second item
Click on 'Back' button on the first item
Flow 2:
Click on SET
Rotate screen
Click on Back
Just to be clear, spinner values are exist and if drop it down you'll found the names (and I have android:configChanges="keyboardHidden|orientation|screenSize" in my manifest).
So, why spinner value is disappear after those flows ?
Here is my code:
Names.java
public class Names
{
private String name;
private int nameIndex;
private Boolean isNameOnTop;
public Names()
{
name = "";
isNameOnTop = true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNameIndex() {
return nameIndex;
}
public void setNameIndex(int nameIndex) {
this.nameIndex = nameIndex;
}
public Boolean getIsNameOnTop() {
return isNameOnTop;
}
public void setIsNameOnTop(Boolean isNameOnTop) {
this.isNameOnTop = isNameOnTop;
}
}
MainActivity.Java
public class MainActivity extends Activity
{
ArrayList<Names> namesArray = new ArrayList<>();
ListView lvNames;
ListviewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvNames = (ListView) findViewById(R.id.listView);
adapter = new ListviewAdapter(this, namesArray);
lvNames.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add)
{
namesArray.add(new Names());
adapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
}
ListviewAdapter.java
public class ListviewAdapter extends BaseAdapter
{
public Activity context;
public LayoutInflater inflater;
private ArrayList<Names> namesID;
private boolean isDeleted;
public ArrayList<Names> getNamesID() {
return namesID;
}
public void setNamesID(ArrayList<Names> namesID) {
this.namesID = namesID;
}
// Constructor
public ListviewAdapter(Activity context, ArrayList<Names> names)
{
super();
setNamesID(names);
this.context = context;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return getNamesID().size();
}
#Override
public Names getItem(int position) {
return getNamesID().get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder
{
RelativeLayout relativeLayout_Upper;
RelativeLayout relativeLayout_Bottom;
Spinner spNames;
Button btn_set, btn_remove, btn_back;
TextView tvChosen;
int index;
}
#Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_row, null);
holder.relativeLayout_Upper = (RelativeLayout) view.findViewById(R.id.lvRow_upper_layout);
holder.relativeLayout_Bottom = (RelativeLayout) view.findViewById(R.id.lvRow_bottom_layout);
holder.spNames = (Spinner) view.findViewById(R.id.spNames);
holder.btn_set = (Button) view.findViewById(R.id.btn_set);
holder.btn_remove = (Button) view.findViewById(R.id.btn_remove);
holder.btn_back = (Button) view.findViewById(R.id.btn_back);
holder.tvChosen = (TextView) view.findViewById(R.id.tv_chosen);
view.setTag(holder);
}
else
holder = (ViewHolder) view.getTag();
holder.index = i;
if (isDeleted)
{
holder.spNames.setSelection(getItem(holder.index).getNameIndex());
holder.tvChosen.setText("Chosen: " + getItem(holder.index).getName());
if (getItem(holder.index).getIsNameOnTop())
{
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
}
else
{
holder.relativeLayout_Upper.setVisibility(View.GONE);
holder.relativeLayout_Bottom.setVisibility(View.VISIBLE);
}
}
// pop spinner names
String[] names = new String[]{"Tom", "Ben", "Gil", "Adam", "Moshe", "Adi", "Michael", "Yasmin", "Jessica", "Caroline", "Avi", "Yael"};
final ArrayAdapter<String> spNamesAdapter = new ArrayAdapter<String>
(view.getContext(), android.R.layout.simple_spinner_dropdown_item, names);
spNamesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spNames.setAdapter(spNamesAdapter);
holder.spNames.setSelection(getItem(holder.index).getNameIndex());
holder.spNames.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//holder.spNames.setTag(position);
getItem(holder.index).setNameIndex(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.btn_set.setTag(i);
holder.btn_set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getItem(holder.index).setName(holder.spNames.getSelectedItem().toString());
int position = (Integer) v.getTag();
holder.tvChosen.setText("Chosen: " + getItem(position).getName());
holder.relativeLayout_Upper.setVisibility(View.GONE);
holder.relativeLayout_Bottom.setVisibility(View.VISIBLE);
getItem(holder.index).setIsNameOnTop(false);
}
});
// remove
holder.btn_remove.setTag(i);
holder.btn_remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
namesID.remove(position);
notifyDataSetChanged();
isDeleted = true;
}
});
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
}
});
return view;
}
}
activity_main.xml: contain ListView only.
upper_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spNames" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SET"
android:id="#+id/btn_set" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REMOVE"
android:id="#+id/btn_remove" />
</LinearLayout>
bottom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Chosen:"
android:id="#+id/tv_chosen"
android:layout_marginRight="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BACK"
android:id="#+id/btn_back" />
</LinearLayout>
listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvRow_upper_layout">
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/upper_view"
android:id="#+id/includeRow_register"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
</RelativeLayout>
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvRow_bottom_layout"
android:visibility="gone">
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/bottom_view"
android:id="#+id/includeRow_showData"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp" />
</RelativeLayout>
</LinearLayout>
In your ListviewAdapter, change:
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
}
});
to:
// back
holder.btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.relativeLayout_Upper.setVisibility(View.VISIBLE);
holder.relativeLayout_Bottom.setVisibility(View.GONE);
getItem(holder.index).setIsNameOnTop(true);
notifyDataSetChanged();
// OR you can use this
// holder.spNames.requestLayout();
}
});
Whenever you click on "Add" in the method onOptionsItemSelected() you add an object new names() into the list, and in the Names class, the value of attribute name is set to ""
I guess that's why you getting an empty item in the spinner.

ListView setOnItemClickListener doesn't response

i try to get selected item from ListView but i dont get any respone from my listener
I dont get any calls at my log from this code:
public void onItemSelected(AdapterView<?> spinnerReference,
View rowReference, int arg2, long arg3) {
chooseExercise = itemsList.getSelectedItem().toString();
Log.i("choosed", chooseExercise);
}
My adapter:
public void setItemList(String muscle)
{
if (muscle.equals("All"))
items = data.getAllExercies();
else
items = data.getMuscleEx(muscle);
ArrayAdapter<CharSequence> exerciseAdapter;
if (items == null || items.length < 1)
items = new String[] {};
exerciseAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, items)
{
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
String text = items[position];
TextView listItem = new TextView(AddWorkOutPage.this);
listItem.setBackground(getResources().getDrawable(R.drawable.shape_box));
listItem.setTextSize(18);
listItem.setText(text);
listItem.setPadding(10, 20, 0, 20);;
listItem.setTextColor(Color.BLACK);
return listItem;
}
};
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
searchItemField.setAdapter(exerciseAdapter);
itemsList.setAdapter(exerciseAdapter);
}
My listview object code:
public void addExerciseDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose exercise");
View prefView = View.inflate(this, R.layout.choose_from_list, null);
searchItemField = (AutoCompleteTextView) prefView.findViewById(R.id.searchItemField);
itemsList = (ListView) prefView.findViewById(R.id.itemsList);
searchItemField.setDropDownHeight(0);
searchItemField.addTextChangedListener(this);
setItemList(wantedMuscle);
itemsList.setOnItemClickListener(this);
builder.setPositiveButton("Choose selected", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Log.i("exercise choose", chooseExercise);
dialog.dismiss();
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.dismiss();
}
});
builder.setNeutralButton("filter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
createDialog();
}
});
builder.setView(prefView);
builder.show();
}
My dialog XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:descendantFocusability="beforeDescendants"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#android:drawable/ic_menu_search" />
<ListView
android:id="#+id/itemsList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/searchItemField"
android:descendantFocusability="beforeDescendants"
android:layout_marginTop="5sp" >
</ListView>
<AutoCompleteTextView
android:id="#+id/searchItemField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imageView1"
android:ems="10" >
<requestFocus />
</AutoCompleteTextView>
</RelativeLayout>
What Listener are you using exactly? The OnItemClickListener has a method onItemClick() instead of your onItemSelected(). I'm not sure if yours would work too, but this works:
ListView listview = (ListView) v.findViewById(R.id.itemsList);
listview.setAdapter(...);
listview.setOnItemClickListener(new MyOnItemClickListener());
And the OnItemClickListener as an inner class:
private class MyOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Object o = parent.getItemAtPosition(position);
}
}

press button in each list in ListActivity

I want to make application that when press the button it will make each sound and each button contain in list (like this pic : enter link description here) so I wrote Im_SensShow.java which extends ListActivity and have imsen_main.xml and imsen_row.xml and it doesn't work(force close) please help
package com.android.proj; public class Im_SensShow extends ListActivity {
/** Called when the activity is first created. */
private DBAdapter db ;
private Cursor cursor ;
private static final int INSERT_ID = Menu.FIRST;
private static final int CHANGE_ID = Menu.FIRST + 1;
private static final int EDIT_ID = Menu.FIRST + 2;
private static final int DELETE_ID = Menu.FIRST + 3;
//this will store situation id that is sent from main
private long thim_sens_id;
private ImageButton menuCarBtn;
TextView MyOutputText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imsen_main);
MyOutputText = (TextView)findViewById(R.id.OutputText);
db = new DBAdapter(this);
setBinding();
//setOnEvent();
listData();
registerForContextMenu(getListView());
}
private void setBinding(){
//Binding Objects
menuCarBtn = (ImageButton)findViewById(R.id.menuCarBtn);
}
private void listData(){
db.open();
Bundle dataBundle = Im_SensShow.this.getIntent().getExtras();
thim_sens_id = dataBundle.getLong("THIMSENSID");
cursor = db.getIm_Sen_List(thim_sens_id,1);
MyOutputText.setText(thim_sens_id+"t");
startManagingCursor(cursor);
ListAdapter list = new SimpleCursorAdapter(
this,
R.layout.imsen_row,
cursor,
new String[] {DBAdapter.KEY_IM_SENS, DBAdapter.KEY_READING},
new int[] {R.id.im_sens, R.id.reading});
setListAdapter(list);
db.close();
menuCarBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), "hello", Toast.LENGTH_LONG).show() ;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID,0, R.string.menu_insert);
menu.add(0, CHANGE_ID,0, R.string.menu_change_lan);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case INSERT_ID:
Cursor c = cursor;
Intent create_Im_Sens = new Intent(Im_SensShow.this,Im_SensShow.class);
Bundle dataBundle = new Bundle(0);
// we want to create record in sit 2 so send a sit 1 primary key is enough
dataBundle.putLong("THIMSENSID", thim_sens_id);
//send 0 since we will notify create activity that this is for create : data does not exist in sit 2 table yet
dataBundle.putLong("IMSENSID", 0);
create_Im_Sens.putExtras(dataBundle); //
startActivity(create_Im_Sens);
break;
case CHANGE_ID:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = { "อังกฤษ", "ฝรั่งเศส", "เยอรมัน",
"อิตาลี", "สเปน", "แสดงทุกภาษา" };
builder.setTitle("เลือกภาษาที่แสดง");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Toast.makeText(getApplicationContext(), items[item],
// Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
default:
break;
}
return true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("จัดการข้อมูล");
menu.add(0, EDIT_ID, 0, R.string.menu_edit);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
/*
#Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case EDIT_ID:{
Cursor c = cursor;
Intent edit_Th_Im_Sens = new Intent(Im_SensShow.this,Th_Im_SensEdit.class);
Bundle bundle = new Bundle();
bundle.putLong("SITUATION2ID", sit2_id);
bundle.putLong("THIMSENSID", c.getLong(c.getColumnIndexOrThrow(DBAdapter.KEY_TH_IM_SENS_ID)));
bundle.putString("THIMSENS",c.getString(c.getColumnIndexOrThrow(DBAdapter.KEY_TH_IM_SENS)));
edit_Th_Im_Sens.putExtras(bundle);
startActivityForResult(edit_Th_Im_Sens,1);
return true;
}
case DELETE_ID:{
db.open();
db.deleteRecord(DBAdapter.TH_IM_SENS_TABLE,DBAdapter.KEY_TH_IM_SENS_ID,cursor.getLong(cursor.getColumnIndexOrThrow(DBAdapter.KEY_TH_IM_SENS_ID)));
Toast.makeText(getBaseContext(), getString(R.string.save_data), Toast.LENGTH_LONG).show() ;
listData();
return true;
}
}
return super.onContextItemSelected(item);
}
/*
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor c = cursor;
c.moveToPosition(position);
Intent showTh_Im_Sens = new Intent(Th_Im_SensShow.this,Th_Im_SensShow.class);
Bundle dataBundle = new Bundle(0);
dataBundle.putLong("SITUATIONID", 0);
showTh_Im_Sens.putExtras(dataBundle); //
startActivity(showTh_Im_Sens);
}
*/
#Override
public void onResume(){
super.onResume();
listData();
}
}
imsen_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:text="ค้นหา "
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<AutoCompleteTextView
android:text=""
android:id="#+id/AutoCompleteTextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</AutoCompleteTextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#98CAF3">
<TextView
android:text="imsentences"
android:id="#+id/TextView03"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="27dip"
android:textColor="#FFFFFF"
android:textColorHighlight="#98CAF3">
</TextView>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:footerDividersEnabled="true"
android:cacheColorHint="#00000000"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/im_sens"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1."/>
imsen_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="#+id/lang"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1."
android:textSize="16dip" />
<TextView android:id="#+id/im_sens"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1."
android:textSize="24dip" />
<TextView android:id="#+id/reading"
android:layout_width="fill_parent"
android:textSize="24dip"
android:layout_height="wrap_content"
android:text="reading"
android:layout_weight="1."/>
<ImageButton
android:id="#+id/menuCarBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/car"
android:background="#null"
/>
You need a custom adapter for the list in which you have a holder for each list item which holds the items and allows them to be pressed and have listeners... etc.
Check out this SO thread.
Android: ListView elements with multiple clickable buttons
In the first answer on the page, he has a link to his blog which does a good job explaining and also has a link to the android developer page where they write a custom adapter.

Categories

Resources