The Background: I've got a dialog that I'm populating with three ListViews, and when the user selects an item from either of those ListViews the dialog should dismiss itself. The ListView items also have long click behavior. This dialog has no buttons. I have no issues with displaying these ListViews.
The Goal: What I would like to do is close the dialog out of scope of the Java method in which I inflate the layout.
The Problem: I'm not quite sure how to do this. Currently my onClick method looks like this:
trigFunctionList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String text = trigFunctionStrings.get(position);
input.append(text + "(");
sysInput += text + "(";
}
});
And this is located out of scope of the method in which I declare my dialog. I would like to keep it this way, but I'm not sure how. Is such a thing possible? If so, thanks in advance for answers given.
Related
I am trying to change the color of the first row in "monitoredpatientlsit" which is a list view. The change should happen if I click on an item in allpatientslist and it already exists in monitoredpatient. So suppose I click on item 3, which also happens to be item 3 in monitoredpatients. I expect the code to change the color of the first view in monitored patient to red. However it doesn't, and I think it has to something to do with "notifydatasetchanged" method, because when I comment it out, it would work the way I want it to, but when I put it back to the code, there are no changes in the color at all. Any Idea why?
allpatientslist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (selectedpatients.contains(allpatients.get(position))){
selectedpatients.remove(selectedpatients.indexOf(allpatients.get(position)));
refomatToRed();
monitoredPatientListAdapator.notifyDataSetChanged();
view.setBackgroundColor(Color.parseColor("#F4F6F1"));
}else{
view.setBackgroundColor(Color.parseColor("#B0D880"));
selectedpatients.add(allpatients.get(position));
monitoredPatientListAdapator.notifyDataSetChanged();
}
}
});
public void refomatToRed(){
monitoredpatientslist.getChildAt(0).setBackgroundColor(Color.RED);
}
Edit:
I fixed it by just implementing the change of color inside the adaptor, since every time an item is removed by view due to the scrolling feature, the item is actually destroyed and will lose any formatting down to it.
When you call notifyDataSetChanged() on the adapter, the list is re-drawn. Changing the color of the first child has no effect because this child is destroyed at the following line.
Try inverting the lines like this:
monitoredPatientListAdapator.notifyDataSetChanged();
refomatToRed();
I have searched through StackOverflow, but have not found a proper answer yet.
I have created a ListView (iteration of a checkbox + itemview) and populated it through my customAdapter (which extends BaseAdapter).
I have a button which takes the values and print it on the screen via a Toast.
So far, so good.
Next step, I still have the button in the MainActivity, but the ListView is now in a child activity that I reach by clicking an image (ImageView placed in the MainActivity). I can still check the checkboxes, but I face two issues:
I am still not able to pass the values to the MainActivity, where they will be printed on screen (or manipulated)
As soon as I press the back button to go back to the MainActivity and I press again the image, every CheckBox that was checked is not checked anymore (they came back to default state)
I don't think that code is needed, as it comes from a standard implementation (ListView - customAdapter with ViewHolder implementation, ...), but in case just let me know.
Thanks a lot in advance!
You can put which checkboxes are checked into sharedpreferences. Then move the listview initialization code to Activity's onResume method.
Sample class to handle sharedpreferences data:
class DataHandler {
private final SharedPreferences dataStore;
DataHandler(Context mContext) {
dataStore = mContext.getSharedPreferences("appname", Context.MODE_PRIVATE);
}
int which() {
return dataStore.getInt("some_key",0);
}
void setCheckedItem(int itemwhat) {
dataStore.edit().putInt("some_key",itemwhat).apply();
}
}
For multiple values, you can put them into an array then convert them to string using toString() method and save. And, to get the values:
String x = "2,3,4,5"; //assume
String[] y = new String[]{x};
int checkablepositions = Integer.parseInt(y[0]); // y[0]....y[y.length-1]
Now, at MainActivity's onResume(), Assume that you have initialized ListView as 'mainList'.
CheckBox x1y2z3 = (CheckBox)mainList.getChildAt(new DataHandler(getBaseContext).which());
x1y2z3.setChecked(true);
And for Saving item,
I would recommend you to show them in an alert-dialog instead of in a Toast. Then set a Positive button to get the values from below code and save them.
Or, if you directly save the values from listview onClick :
mainList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
new DataHandler(getBaseContext()).setCheckedItem(position);
}
});
That's it. I'm really new at programming (as you can see my StackOverFlow rep) but hope it will be able to help you.
The main concept is to : store the value → get the value → parse the value → show it on UI.
I want to thank you in advance for the solution to my question.
I have a custom adapter for my listview. the list item has an imageView(1), a progressBar(3), and a download button(2).
When the download button for each list item is clicked, I grab vital details of the listitem such as the position of the view, the resourceid of the button, the resource id of imageview and the resource id of progress bar, then i make an parcealable object of class "Download".
Download download = new Download();
download.setUrl(url);
download.setButtonResource(this.downloadBt.getId());
download.setCreativeWork(creativeWork);
download.setDownloadBt(this.downloadBt);
download.setProgressBarResource(this.progressBar.getId());
download.setProgressBar(this.progressBar);
download.setContext(activity);
download.setViewResource(view.getId());
Intent intent = new Intent(activity, BroadcastService.class);
intent.putExtra("download", download);
Log.e("download button", url);
activity.startService(intent);
I start a service which does the download and reports back using a broadcast. When this broadcast message is received I want to update the progress bar.
My problem is how to get the progress bar concerned from my mainactivity which receives the message. How do I reference this?
I am currently using a parcelable object to pass the resource id for the progressbar, all the way from the adapter to the service, then to the receiving activity(mainActivity) using the intent's putExtra(), then I do this at the mainActivity
Download download = (Download)intent.getParcelableExtra("download");
ProgressBar progressBar = (ProgressBar)findViewById(download.getProgressBarResource());`
The issue here is that always only returns the first item of the list, regardless of which listitem is clicked. I would want to get each unique listitem and update the progress bar and the download button. Thanks
I am assuming that you show this layout in a ListView or RecyclerView. First thing that need to do is, add a field for index in your Download class to identify the position in the list from where that button was pressed. Next, pass the index from your getView() or onBindViewHolder() to the function that creates the Download object and add that index to the object.
When you receive the when you broadcast any update from your Service, do include the index value. Now, in your code in your activity where you receive the broadcast value, extract the value of index and the progress. Now, you could write something like this to update the progress of that view in the list:
int index = ... //some value you received in broadcast
int progress = ...//some value you received in broadcast
View view = listView.getChildAt(index);
if (view != null) {
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
if (progressBar != null) {
progressBar.setProgress(progress);
}
}
This can be one of the solution to your problem
First You need to pass progress value to the adapter that may be zero in start.
Implement setOnItemClickListener for your listview
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
//now point to your item position and do your stuff here
}
});
When ever you receive broadcast for download progress. Just update your ListView by Nullifying previous items with new items containing download progress values.
Not sure if this is what you looking for...
In you adapter. do below.. (I take a sample from my project which do a delete card from the list, when the delete button is clicked)
In getView function inside adapter.
Card card = list.get(position);
viewHolder.imgDelete.setTag(card);// --> i set the whole card info to tag
outside the adapter.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
if (id == R.id.iv_delete_card) {
//System.out.println("---> Card: " + tag);
//delete card
Object tag = v.getTag();
if (tag != null && tag instanceof Card) {
promptDeleteCard((Card) tag);
}
}
}
I have a ListView of Medications that use a CursorAdapter. My goal is to obtain a reference to the Cursor of the selected item when the user presses the submit button, but I keep getting a null value. Here is my current code:
mSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor selectedMedication = (Cursor) mMedicationListView.getSelectedItem();
if(selectedMedication != null)
{
MedicationSelectionListener activity = (MedicationSelectionListener) getActivity();
activity.onMedicationSelected(new Medication(selectedMedication));
} else{
Toast.makeText(getActivity(), "Must select a medication.", Toast.LENGTH_SHORT).show();
}
}
});
When this executes, selectedMedication is always null. I have implemented a drawable selector.xml file that changes the background color of the item when it is pressed, and that works fine, so I was under the impression that clicking the item was enough.
I have also tried the following, by setting the selected medication variable each time an item is clicked:
mMedicationListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor) mMedicationListView.getItemAtPosition(position);
if(c.moveToFirst())
mSelectedMedication = new Medication(c);
}
});
This worked fine, but I felt it preformed a bunch of pointless operations when all I am interested in is the final selected item. Should clicking an item trigger mMedicationListView.onItemSelected()? If not, what action is used to ensure that happens?
so I was under the impression that clicking the item was enough.
Clicks are not selections with a ListView. A selection will occur either when:
you set a selection programmatically, or
the user uses a five-way navigation option (e.g., D-pad, trackball, arrow keys) and presses up/down on that to move a highlight bar around
all I am interested in is the final selected item
A ListView is a command widget by default. When the user taps on a row in a ListView, your app should go do something, usually getting rid of the ListView along the way.
If, OTOH, the user is choosing something, where the list and choice remain on-screen (e.g., master-detail pattern, choosing a state/province as part of filling in an address), then you should be using a choice mode. That could be a single-choice mode (usually represented with radio buttons down the right edge), multiple-choice mode (usually represented with checkboxes down the right edge), or multiple-choice-modal mode (usually represented by an "activated" state setting a persistent highlight, usually reserved for master-detail sorts of scenarios).
Do not attempt to overload "selection" to mean "choice". It sounds like you are presenting a ListView as part of something larger, where the user is making a choice, so use a choice mode for that.
You can find my code here:
How to correctly build table with data using onPostExecute and ListView
I need to do loading data from the server when my ListView is scroll to the bottom. I tried to looking for solution on Stackoverflow, but it is not helpful for me.
Also if it's not difficult i like to know how it's work for understand all.
Thank's to all
You have 2 solutions:
1) With OnScrollListener
You must have a class that extends ListView and implements OnScrollListener.
When you initialise the view, set it as the scroll listener :
setOnScrollListener(this);
Implement the method onScroll. It's called when you scroll with the arguments firstVisibleItem, visibleItemCount and totalItemCount.
When firstVisibleItem+visibleItemCount==totalItemCount you reached the bottom of the list, you can call your AsyncTask again to load the next items.
2) With a custom adapter
In the method getView that you must overwrite, you have access to the position of the item being rendered, i.e. about to be visible on the screen.
Let's say you store your items in a List items you know when you reached the bottom of the list when position == items.size()-1. You can then call your AsyncTask.
Warning
Be careful with these 2 solutions, if all the items of the list fit in the screen, your AsyncTask may be called very often and for no reason. You must do the necessary checks for that before starting it.
Use the Scroll state change listener in your program...I hope It will help you definitely ....
listStudies.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (Logic Condition) {
//Here also You can do your Logic here and then you can achieve your wishes.....
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (Logic Condition) {
//You just do your Logic here and then you can achieve your wishes.....
}
}
});