2 ListView in a ListFragment only one onListItemClick - android

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

Related

Android - Listview Selected Item

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

How can I isolate cells within my ListView row for use with setOnItemClickListener instead of the entire row?

I have a list of people that I am pulling from the database with a [modified] SimpleCursorAdapter. I then iterate over the cursor and print information out in a ListView in my app. Right now, it is coded so that when I click on a row, my app performs a function. However, what I would like to do is make it so that when I click on an icon within the row, my app will perform the appropriate function.
Where I am having trouble is isolating a cell within the row for the setOnItemClickListener instead of the entire row.
How do I go about isolating an ImageView within the row instead of the entire row itself?
Here is what I have:
Home.java
package myPackage;
public class Home extends Fragment {
private View rootView;
private AlternateRowColorSimpleCursorAdapter mySimpleCursorAdapter;
private ViewPager myViewPager;
private SwipeRefreshLayout studentSwipeRefresh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.home, container, false);
myViewPager = (ViewPager) getActivity().findViewById(R.id.pager);
studentSwipeRefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.student_swipe_refresh);
return rootView;
}
#Override
public void onViewCreated(View rootView, Bundle savedInstanceState) {
super.onViewCreated(rootView, savedInstanceState);
drawTheStudentView();
studentSwipeRefresh.setColorSchemeColors(Color.parseColor(Constants.RED), Color.parseColor(Constants.ORANGE), Color.parseColor(Constants.YELLOW), Color.parseColor(Constants.GREEN), Color.parseColor(Constants.BLUE), Color.parseColor(Constants.INDIGO), Color.parseColor(Constants.VIOLET));
studentSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
studentSwipeRefresh.setRefreshing(false);
drawTheStudentView();
}
});
}
private void drawTheStudentView(){
DatabaseHelper myDBHelper = new DatabaseHelper(getActivity());
Cursor studentCursor = myDBHelper.getStudentsCursor();
String[] fromColumns = {"_id","studentID","status","location"};
int[] toViews = {R.id.student_number_textview, R.id.student_id_textview};
mySimpleCursorAdapter = new AlternateRowColorSimpleCursorAdapter(getActivity(), R.layout.student_layout, studentCursor, fromColumns, toViews, 0);
// Replace the _id column with a student count
mySimpleCursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
String counter = Integer.toString((cursor.getPosition()+1));
TextView modifiedTextView = (TextView) view;
if(columnIndex == 0){
modifiedTextView.setText(counter);
return true;
}
return false;
}
});
ListView myListView = (ListView) rootView.findViewById(R.id.student_row);
// Listen for somebody clicking on a Student ID, and process
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor subCursor = (Cursor) mySimpleCursorAdapter.getItem(position);
String zapNumber = subCursor.getString(subCursor.getColumnIndex("studentID"));
StudentStatus studentStatus = (StudentStatus) getFragmentManager().findFragmentByTag(getFragmentTag(Constants.TAB_INDEX_PATIENT_VITALS));
studentStatus.setZapNumber(zapNumber);
myViewPager.setCurrentItem(Constants.TAB_INDEX_PATIENT_VITALS);
}
});
// Draw the list
myListView.setAdapter(mySimpleCursorAdapter);
myDBHelper.close();
}
// Pass me a tab index (see Constants.java) and I'll return a refrence to that tab.
private String getFragmentTag(int tagID){
return "android:switcher:" + R.id.pager + ":" + tagID;
}
}
AlternateRowColorSimpleCursorAdapter.java
package myPackage;
public class AlternateRowColorSimpleCursorAdapter extends SimpleCursorAdapter {
public AlternateRowColorSimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = super.getView(position, convertView, parent);
if(position % 2 == 0){
row.setBackgroundColor(Color.parseColor(Constants.WHITE));
} else {
row.setBackgroundColor(Color.parseColor(Constants.LIGHTGREY));
}
return row;
}
}
student_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="#+id/student_number_textview"
android:typeface="monospace"
android:layout_weight="1"
android:textStyle="bold"
style="#style/StudentStyle" />
<TextView
android:id="#+id/student_id_textview"
android:typeface="monospace"
style="#style/StudentStyle" />
<ImageView
android:id="#+id/student_status_button"
style="#style/studentIconLink"
android:src="#drawable/status_icon"/>
<ImageView
android:id="#+id/student_location_button"
style="#style/studentIconLink"
android:src="#drawable/location_icon"/>
</LinearLayout>
A possibility to define a callback interface for communication between the views created in your Adapter and your Fragment.
Have your Fragment implement this interface and pass in a reference to your Fragment in your Adapter's constructor. In your getView() method in the adapter, you can set an OnClickListener on your ImageView that you want to listen for, and then trigger the callback you passed into your Adapter. Note: you can pass back something like position in this callback so you know which row's ImageView was selected.

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

Generate background colour in listView from database

I have a listView generated from a database, is there a way to make a background colour or a picture to each "section" in the list:
if the first symbol in "Tip" is "W" the background should be Green, and if its "L" it should be red
Im thinking something like this, but i have no idea where to put it since it have to be done in every section:
tipvalue = BetsDbAdapter.KEY_TIP;
//Here to split the value to gain only "W" or "L"
String arrtip[] = tipvalue.split(" ", 2);
temptip = arrtip[0];
//then set background
if (temptip.equals("W")) {
getWindow().getDecorView().setBackgroundColor(Color.GREEN);
To the left is my listView and right is the xml file to make each "section" in the listview
Here is my database:
This is code generating the listView
public class StoredBets extends Activity {
private BetsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
dbHelper = new BetsDbAdapter(this);
dbHelper.open();
}
#Override
public void onStart(){
super.onStart();
displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.results, menu);
return true;
}
public void testknap1(View v) {
Intent myIntent = new Intent(StoredBets.this, Overview.class);
startActivity(myIntent);
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllStats();
String[] columns = new String[] {
BetsDbAdapter.KEY_SMATCH,
BetsDbAdapter.KEY_TIP,
BetsDbAdapter.KEY_BETAMOUNT,
BetsDbAdapter.KEY_BODDS
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.smatch,
R.id.tip,
R.id.bodds,
R.id.betamount,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.storedbets,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView2);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String betMatch =
cursor.getString(cursor.getColumnIndexOrThrow("smatch"));
Toast.makeText(getApplicationContext(),
betMatch, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(StoredBets.this, SetWinVoidLoss.class);
myIntent.putExtra("id", id);
startActivity(myIntent);
}
});
}
}
EDIT 2:
#amal
This is the layout(results.xml) with the listview
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".StoredBets" >
<ListView
android:id="#+id/listView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/button1" >
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="180dp"
android:onClick="testknap1"
android:text="Button" />
</RelativeLayout>
you can get a fair idea from my code,
code snippet for displaying ListViews where the "curSelected" item has a different background:
final ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(new BaseAdapter()
{
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = new TextView(ListHighlightTestActivity.this);
convertView.setPadding(10, 10, 10, 10);
((TextView)convertView).setTextColor(Color.WHITE);
}
convertView.setBackgroundColor((position == curSelected) ?
Color.argb(0x80, 0x20, 0xa0, 0x40) : Color.argb(0, 0, 0, 0));
((TextView)convertView).setText((String)getItem(position));
return convertView;
}
public long getItemId(int position)
{
return position;
}
public Object getItem(int position)
{
return "item " + position;
}
public int getCount()
{
return 20;
}
});
This is a tutorial of how to write an adapter for a list view. amal is right, you can change the separate items in the list view in the getView() method.

ListFragment onItemClickListener not working

I'm using the tabbed layout (with swipe).
Here I have 3 tabs with controlled by a SectionsPagerAdapter. Each tab is a ListFragment.
Now I want to get an event fired when one of the items in the list is clicked. I would like a listener for each tab.
Here's the code now (Which isn't working, event is not fired).
public class NyhederFragment extends ListFragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private static final String TAG="NyhederFragment";
private List<Item> newsItems;
private ArrayList newsHeadlines;
private ArrayAdapter adapter;
private BroadcastReceiver updateReciever;
public NyhederFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ListView newsList = new ListView(getActivity());
newsList.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
newsList.setId(R.id.list);
DatabaseHelper dbConn = new DatabaseHelper(getActivity());
newsItems = dbConn.getAllItemsFromNews();
newsHeadlines = new ArrayList();
for(Item i : newsItems){
newsHeadlines.add(i.getTitle());
}
adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, newsHeadlines);
setListAdapter(adapter);
newsList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("debug", "single click");
}
});
dbConn.close();
getActivity().registerReceiver(updateReciever, new IntentFilter("ArticlesUpdated"));
return newsList;
}
}
What is it, I'm doing wrong?
Thanks a lot in advance!
If you are using ListFragment then you can simply use its override method onListItemClick()
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
It is due to custom list item. The default focus is with custom list item (button/textview). It causes this issue.
Please add android:descendantFocusability="blocksDescendants" in root layout of list element.
Hope this will help someone.
change setListAdapter(adapter); to newsList.setAdapter(adapter);
If you wanted to create or re-use or an existing handler that implements AdapterView.OnItemClickListener, rather than implementing onListItemClick() within the ListFragment, you can do so by getting a reference to the ListView of the ListFragment and setting its listener. In your ListFragment.onResume() you could do:
#Override
public void onResume() {
super.onResume();
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("TAG", "Stop touching me");
}
});
}
In my case, I can use the same listener from an Activity with a ListView, a ListActivity or a ListFragment, e.g.
listView.setOnItemClickListener(new MyListViewOnClickListener(getActivity()));

Categories

Resources