Android - Listview Selected Item - android

I made a listview and I wanted to make an user input a choice. How can I do this? Atm I only managed to create the ListView and display the data.
Is there an easy way to get the value of a selected item of the ListView and use it later? Something like a ListView RadioButton.
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"
tools:context="com.example.tiagosilva.amob_android.TubeDataArchive" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv_tubeData"
android:choiceMode="singleChoice">
</ListView>
Listview:
public class TubeDataArchive extends Fragment {
public TubeDataArchive() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tube_data_archive, container, false);
ListView tubeDataList = (ListView) view.findViewById(R.id.lv_tubeData);
//load tube data
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
String tubeDataString = settings.getString("tubeData", "");
String[] tubeDataSplit = tubeDataString.split("\n");
List<String> tubeDataItems = new ArrayList<>();
for(int i=0; i<tubeDataSplit.length;i++)
{
tubeDataItems.add(tubeDataSplit[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, tubeDataItems);
// Assign adapter to ListView
tubeDataList.setAdapter(adapter);
return view;
}
}

Is there an easy way to get the value of a selected item of the
ListView and use it later?
Add onItemClickListener after the for loop.
tubeDataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// do whatever you want
Log.d("############","Items " + tubeDataSplit[arg2] );
}
});
Something like a ListView RadioButton
If you want to have a listview with a radio button, then you need to create a custom listview layout.

Add ItemClickListener to your listview
tubeDataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getapplicationcontext(), tubeDataItems.get(id),
Toast.LENGTH_LONG).show();
}
});

Related

Getting checkable list view into fragment

I am trying to have a checkable list view fragment pop up with a button at the top of the list view. After user clicks an item in the navigation menu, the main activity will be populated with my button and list view fragment. I'm getting 'invoke virtual method' error, even though the element in declared. Here's some code.
My list fragment class:
public class ThingsManager extends Fragment {
ArrayList<String> selectedItems;
ListView checkable_list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(layout.things_manager_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}
public ThingsManager() {
// Required empty public constructor
}
}
List fragment layout:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".ThingsManager">
<TextView
android:id="#+id/things_manager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Things Manager"
android:textSize="25dp"/>
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/checkable_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Should I be controlling the listview in MainActivity or in the FragmentClass ?
Move your all your view initialization and listview setup code from onActivityCreated to onCreateView method.
And your this statement
//create an instance of ListView
checkable_list.findViewById(R.id.checkable_list);
is wrong. You have to find ListView from the view you have inflated in onCreateView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(layout.things_manager_fragment, container, false);
init(rootView);
return rootView;
}
public void init(View rootView){
//create an ArrayList object to store selected items
selectedItems = new ArrayList<String>();
//create an instance of ListView
checkable_list = rootView.findViewById(R.id.checkable_list);
//set multiple selection mode
checkable_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
String[] things_factory = {"Sports", "Politics", "Food", "Television", "Movies", "Fashion",
"Theoretical Physics"};
//supply data itmes to ListView
//ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.things_check, things_factory);
ArrayAdapter<String> aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, things_factory);
checkable_list.setAdapter(aa);
//set OnItemClickListener
checkable_list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// selected item
String selectedItem = ((TextView) view).getText().toString();
if(selectedItems.contains(selectedItem))
selectedItems.remove(selectedItem); //remove deselected item from the list of selected items
else
selectedItems.add(selectedItem); //add selected item to the list of selected items
}
});
}

Disabling click for one data adapter in ListView

I am using CWAC MergeAdapter - https://github.com/commonsguy/cwac-merge to add two data adapters in a ListView. Something like this:
MergeAdapter mergeAdapter = new MergeAdapter();
mergeAdapter.addAdapter(yourFirstAdapter);
mergeAdapter.addAdapter(yourSecondAdapter);
list.setAdapter(mergeAdapter);
I also setup an item click listener for my ListView. However what I want is that only data from adapter1 should be clickable. How can I implement this. What i have so far is this:
ListView list = (ListView) findViewById(R.id.lv);
RelativeLayout secondAdapterlistRowLayout = (RelativeLayout) findViewById(R.id.secondrow);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long mallId) {
//go to the shops view
if (adapterView.equals(secondAdapterlistRowLayout)){
//do nothing
}
else {
Intent intent = new Intent(getActivity(), ShopActivity.class);
intent.putExtra("MALL_ID", (int) mallId);
startActivity(intent);
}
}
});
XML -- row2 -- adapter2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F0F0F0"
android:clickable="false"
android:id="#+id/secondrow">
....
</RelativeLayout>
Basically i want to do this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long mallId) {
if(R.id.secondrow is clicked){ then start a new activity }
}
}
The easier way that i found was to get the resource name that was clicked and then compare it with the resource name of the row (i.e. secondrow)
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long mallId) {
if (getResources().getResourceEntryName(view.getId()).equals("secondrow"){
//then do something
}
//otherwise do nothing
}
}
In adapter view use setTag() method to your item and identify that tag when your click on listview any item.

Android - ListFragment OnClickListener is not working

I have a ListFragment in my android application, I have got it to work, but the OnClick Listener is not working, I tried just making it so that when any item on the list is selcted a Toast appears and it is not happening, there is no Error so I have no LogCat to post
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.main, container, false);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
//...
ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
ListView lv = (ListView)v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
Toast.makeText(getActivity().getApplicationContext(), "Not Configured",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
Thanks
if your class extends ListFragment than everything you need to do is just overriding its onListItemClick method.
#Override
public void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
Toast.makeText(getActivity(), "Item " + pos + " was clicked", Toast.LENGTH_SHORT).show();
}
The ListFragment subclass already has it's overriden onListItemClick method.
The doc says:
This method will be called when an item in the list is selected. Subclasses should override
So there is no need to declare another listner for your listview.
Removing .getApplicationContext() should work. I have some code similar to yours from an app I made. Its from inside a fragment as well though works without problem. The db.remove is probably irrelevant to your code though because this code was written for an app with a database. Also maybe try changing new OnItemClickListener to new AdapterView.OnItemClickListener
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
db.remove( (int) l);
Toast.makeText(getActivity(), "Item Deleted", Toast.LENGTH_LONG).show();
}
});
If that doesn't work, maybe try making a Context instance variable like:
private Context ctx = getActivity();
or
private final Context ctx = getActivity();
I have never worked with ListFragments before though, so I am not sure if anything I wrote will work.
put
android:focusable="false"
android:clickable="false"
to all itens in your row
Make sure you
1.shouldn't have onclicklistener inside your Adapter
2.inside your XML layout
R.layout.main
Listview should be initialized like
<ListView
android:onClick="#id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/textHeader"
android:layout_margin="5dp"
android:divider="#color/DeepPink"
android:dividerHeight="1sp"
android:gravity="center"
android:horizontalSpacing="1dp"
android:visibility="visible" >
here id android:onClick="#id/list" important
ListView should be initialize like ListView lv = getListView if your extending your fragment by ListFragment instead Fragment

2 ListView in a ListFragment only one onListItemClick

As I mentioned in the title, I have 2 ListView (lets call them A and B) in a ListFragment and only one onListItemClick.
When I click on a row of List A, my onListItemClick is called fine. But when I click on a row of List B, nothing happens.
This is what I have:
<!-- LIST A -->
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<!-- Separator -->
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<!-- LIST B -->
<ListView
android:id="#+id/listCompany"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
This is my ListFragment:
public class ClientsActivity extends ListFragment {
OnClientSelectedListener mClientListener;
public interface OnClientSelectedListener {
public void onEmployeeSelected(int id);
public void onCompanySelected(int id);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mClientListener = (OnClientSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " you must implement OnClientSelectedListener ");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.e("onListItemClick","called with " + position + " : "+l.getId() + " and " + android.R.id.list);
int id = position;
if (l.getId() == android.R.id.list) {
mClienteListener.onEmployeeSelected(id);
} else if (l.getId() == R.id.listCompany) {
mClienteListener.onCompanySelected(id);
}
}
And then in my main FragmentActivity I implement the interface OnClientSelectedListener. I think this has to be with android:id in my ListViews. I dont know how to invoke onListItemClick when a row of List B is clicked. Any help will be apreciated.
SOLUTION:
In the onCreateView of my ListFragment I have:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_clientes, container, false);
//LIST A
listEmploees(view);
//LIST B
listCompanies(view);
...
}
private void listCompanies(View view){
CompanyqliteDao companyDao = new CompanyqliteDao ();
//I get all the companies from DB
mCursorCompany = companyDao.listCompany(getActivity());
if(mCursorCompany.getCount()>0){
String[] from = new String[] { "name", "phone"};
int[] to = new int[] { R.id.textViewNameIzq, R.id.textViewNameCent };
ListView lvCompanies = (ListView) view.findViewById (R.id.listCompany);
//I have a custom adapter
ListClientCursorAdapter notes = new ListClientsCursorAdapter(contexto, R.layout.activity_fila_cliente, mCursorCompany, from, to, 0);
lvCompanies .setAdapter(notes);
lvCompanies.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
onListItemClick(lvCompanies,view,position,arg);
}
});
}
}
private void listEmploees(View view){
EmployeeSqliteDao employeeDao = new EmployeeSqliteDao();
//Get the list from DB
mCursorEmployee = employeeDao.listEmployees(getActivity());
if(mCursorEmployee.getCount()>0){
String[] from = new String[] { "name", "phone"};
int[] to = new int[] { R.id.textViewNameIzq, R.id.textViewNameCent};
ListView lvEmployees = (ListView) view.findViewById (android.R.id.list);
ListClientsCursorAdapter notes = new ListClientesCursorAdapter(context, R.layout.activity_fila_cliente, mCursorEmployee, from, to, 0);
lvEmployees.setAdapter(notes);
//NOTE THAT I DONT HAVE TO SET A LISTENER FOR THIS ONE, AUTOMATICALLY
// THE onListItemClick IS CALLED
}
You need get reference of your second ListView and you need to attach onItemClickListener to it.
Because ListFragment will attach onItemClckListener for the listView having id #id/android:list
Try to get reference in onCreateView
Edit:
ListView list2=view.findViewById(R.id.listCompany);
list2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
onListItemClick(adapter,view,position,arg);
}
});
You need to change your ListFragment to a Fragment, then reference the two ListViews separately and assign their listeners:
ListView list = (ListView)findViewById(R.id.list);
ListView listCompany = (ListView)findViewById(R.id.listCompany);
list.setAdapter(...)
list2.listCompany(...)
One ListView per ListFragment, or multiple ListViews in one Fragment, but no two ListViews in one ListFragment

Single Choice Lists and onClick events

I have a CHOICE_MODE_SINGLE list with 3 rows. How do I place an onClick event that changes the value of an arbitrary variable, so that if Row 1 is clicked, say, the value of X = 1, and when Row 2 is clicked, the value of X = 2, etc.?
public class List extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
private static final String[] GENRES = new String[] {"Barre", "Buffumville","Hodges"};
}
Its quite simple..rather than extending ListActivity extend it by Activity and just declare listview in your XML file as below:
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
initialize listview in your activity:
ListView listView=(ListView) findViewById(R.id.list);
And after setting adapter as you did,set the item click listener of the listview as below in your code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
Toast.makeText(getBaseContext(), GENRES[position], Toast.LENGTH_SHORT).show();
}
});
By doing this you will get the desired value of that position of listview.
You will surely get the result you want.
You want to set the onItemClickListener on the list view.
listView.setOnItemClickListener(
new OnItemClickListener(
#Override
onItemClick(AdapterView<?> listView, View cell, int position, long id) {
// Code to change variables
}
});
You can implement protected void onListItemClick (ListView l, View v, int position, long id) in your ListActivity, and the position variable lets you know which item was clicked.

Categories

Resources