I am using fragments in my app. Every fragment has a listview. The ListViews are custom listviews containing a single image view.
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="#android:drawable/ic_notification_overlay" />
The listview items are images. I want to implement searchview. I want to search by name of each listview item eg "jingle bells etc" and also by number i.e "1,2. . . and so on.
My java file containing listview titles is.
public class carolFrag extends Fragment {
//code
public carolFrag() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
private static final String TAG = "carolFrag";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup main_content, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_carol, main_content, false);
final int[] menuImage = {R.drawable.carol_1_title, R.drawable.carol_2_title,R.drawable.carol_3_title,R.drawable.carol_4_title,R.drawable.carol_5_title,R.drawable.carol_6_title,R.drawable.carol_7_title,R.drawable.carol_8_title,R.drawable.carol_9_title,R.drawable.carol_10_title,R.drawable.carol_11_title};
final ListView listView = (ListView) view.findViewById(R.id.CarolList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent1 = new Intent (getActivity(), PackageC.class)
intent1.putExtra("position", position);
startActivity(intent1);
}
});
AdapterCarols adapter = new AdapterCarols(getContext(), menuImage);
listView.setAdapter(adapter);
// Inflate the layout for this fragment
return view;
}
}
I am unable to make any logic as the array has drawables in it.
Because the array is full of drawables, and it's not a database thing or anithing every solution you i'll get will be a work around. The simples, i believe, is to have another array maybe an - String[] - with the names of the drawables in the same order they are in the original - final int[] menuImage - you can make the search in the array of String and save the position of the results. Then use those positions to create a new array ( int[] ) putting in this new array the drawables that matches those positions. Finally change the adapter of the list view, passing the array with the results and notifydatachange(); in the listview for it to update visually.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
main_content, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_carol, main_content, false);
final int[] menuImage = {R.drawable.carol_1_title, R.drawable.carol_2_title,R.drawable.carol_3_title,R.drawable.carol_4_title,R.drawable.carol_5_title,R.drawable.carol_6_title,R.drawable.carol_7_title,R.drawable.carol_8_title,R.drawable.carol_9_title,R.drawable.carol_10_title,R.drawable.carol_11_title};
final ListView listView = (ListView) view.findViewById(R.id.CarolList);
SearchView sv = view.findviewById(R.id.searchview);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
public boolean onQueryTextChange(String par1)
{
return false;
}
public boolean onQueryTextSubmit(String par1)
{
int [] searchresults = PerformSearch(par1);
AdapterCarols newadapter = new
AdapterCarols(getContext(), searchresults);
listView.setAdapter(adapter);
listview.invalidate(); // don't remember listview refresh method. I work with Recyclerview, they have a notifyDatasetChange(); method.
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent1 = new Intent (getActivity(), PackageC.class)
intent1.putExtra("position", position);
startActivity(intent1);
}
});
AdapterCarols adapter = new AdapterCarols(getContext(), menuImage);
listView.setAdapter(adapter);
// Inflate the layout for this fragment
return view;
}
private int[] PerformSearch(par1)
{
String [] strcarols = {carol_1_title,carol_2_title,carol_3_title,carol_4_title,carol_5_title,carol_6_title,carol_7_title,carol_8_title,carol_9_title,carol_10_title,carol_11_title};
int[] menuImage = {R.drawable.carol_1_title, R.drawable.carol_2_title,R.drawable.carol_3_title,R.drawable.carol_4_title,R.drawable.carol_5_title,R.drawable.carol_6_title,R.drawable.carol_7_title,R.drawable.carol_8_title,R.drawable.carol_9_title,R.drawable.carol_10_title,R.drawable.carol_11_title};
int[] results = new int[];
int carolsresultcount = 0, index =0;
/// simplest way
for(String carol:strcarols)
{
if(carol.contains(par1))
{
results [carolsresultcount++] = menuImage [index];
}
index++;
}
return results;
}
I hope this can solve your problem.
Related
I'm making an app that makes use of a GridView to display subcategories.
I have the categories displayed on screen and when clicked a dialog appears with a GridView displaying subcategories and a button to view everything in that category.
Here's the problem:
Sometimes the GridView doesn't load on the first click, I have to close it and then click on the category again for it to open. Categories are basically images with a textview on top. Pictures are loaded from the Internet.
Code for Dialog:
public class dialogFragment extends android.support.v4.app.DialogFragment {
private Button mViewAll;
private GridView mSubCatsView;
public ArrayList<category> mCats = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_fragment, container);
mCats.addAll(((shopActivity)getActivity()).mDialogCats);
mViewAll = v.findViewById(R.id.viewAllBTN);
mSubCatsView = v.findViewById(R.id.subCatsView);
final gridAdapter adapada = new gridAdapter(getActivity(), mCats);
mSubCatsView.setAdapter(adapada);
mSubCatsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ArrayList<category> subSubCats = new ArrayList<>();
for (int y = 0; y < ((shopActivity)getActivity()).mCategoriesAll.size(); y++){
if(mCats.get(i).getId() == ((shopActivity)getActivity()).mCategoriesAll.get(y).getParent()){
subSubCats.add(((shopActivity)getActivity()).mCategoriesAll.get(y));
}
}
if(subSubCats.size() > 0){
mCats.clear();
mCats.addAll(subSubCats);
adapada.notifyDataSetChanged();
}
}
});
mViewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return v;
}
}
If anyone else has this problem, I fixed it by using a RecyclerView + GridLayoutManager to mimic a GridView.
I want to start a new activity from list view items from a fragment. But this isn't working. Here's the code:
public class SettingsF extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = (ViewGroup) inflater.inflate(R.layout.fragment_settings, container, false);
String[] menuitems = {"Context Setup", "Set-Up Custom Texts"};
ListView listView = (ListView) root.findViewById(R.id.listview_settings);
ArrayAdapter<String> listViewAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, menuitems);
listView.setAdapter(listViewAdapter);
listView.setOnClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 1){
Intent intent;
intent = new Intent(getActivity(), contactselect.class);
startActivity(intent);
}
}
});
return root;
}
If you want to use event listener on ListView then you can use listview.setOnItemClickListener(new AdapetView). This (setOnClickListener) listener can't work on listview.
Listview contain multiple data.
Try this if you want to open an activity on item clicked:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// your code
}
});
I have a listview and want to set an onClickListener on each item in this fragment but it's not working.I also wanted to set a contextMenu on the listview and that's not working either.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
purchasedItemsView = inflater.inflate(R.layout.purchased_items_fragment , container, false);
db = new StoreDataBase(getActivity() , Consts.StoreDB.DB_NAME , Consts.StoreDB.DB_VERSION);
storeArrayList = new ArrayList<>();
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
adapter .notifyDataSetChanged();
registerForContextMenu(listView);
sendData(purchasedItemsView);
return purchasedItemsView;
}
private void sendData(View view){
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
listView = (ListView) view.findViewById(R.id.storeListView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
}else{
}
}
Don't reinitialize listview after you have done it once in onCreateView(). Therefore, remove this line from sendData() method:
// remove this
listView = (ListView) view.findViewById(R.id.storeListView);
Then you need to move this part of code outside of if statement or inside of onCreateView() method.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
Point 1:
Seems your array list is empty, so fill some data
storeArrayList = new ArrayList<>();
//-------------------------------------
Bundle bundle = getArguments();
if (bundle != null) {
final String[] names = bundle.getStringArray(Constc.Data.names);
if(names != null && names.length() > 0) {
storeArrayList.addAll(names);
}
}
//-------------------------------------
listView = (ListView) purchasedItemsView.findViewById(R.id.storeListView);
adapter = new StoreListViewAdapter(getContext() , R.layout.store_item_row , storeArrayList);
listView.setAdapter(adapter);
Point 2: You don't need "notifyDataSetChanged();" right after you set the adapter.
//adapter .notifyDataSetChanged();
Point 3:
Use long click listener for showing context menu
listView.setOnItemLongClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "long press clicked");
//show dialog or context menu dialog.
}
});
Point 4:
comment the sendData method and use the onclick directly
//sendData(purchasedItemsView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Data" , "clicked");
}
});
Hope this helps.
Vote Up - If you like it.
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.
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()));