I have used popup listview to work like spinner .I want it to pop upwards like spinner does when its at the bottom of the screen .
I have tried :
popupWindowDogs.showAsDropDown(buttonShowDropDown,5,0);
ALSO,
popupWindowDogs.showAsDropDown(buttonShowDropDown, (int)(Math.round(buttonShowDropDown.getX())),-(totallinear_layouts+buttonShowDropDown.getHeight()));
totallinearlayouts = sum of all heights of linear layouts till the button.
This works properly on a few devices but not like Spinner. How can I make it to work like Spinner? I mean to inflate exactly as the size of the device and the list height. I really appreciate any help. Thanks in Advance.
Reference:https://www.codeofaninja.com/2013/04/show-listview-as-drop-down-android.html
MainActivity.java
public class MainActivity extends Activity {
String TAG = "MainActivity.java";
String popUpContents[];
PopupWindow popupWindowDogs;
Button buttonShowDropDown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize pop up window items list
// add items on the array dynamically
// format is DogName::DogID
List<String> dogsList = new ArrayList<String>();
dogsList.add("Akita Inu::1");
dogsList.add("Alaskan Klee Kai::2");
dogsList.add("Papillon::3");
dogsList.add("Tibetan Spaniel::4");
// convert to simple array
popUpContents = new String[dogsList.size()];
dogsList.toArray(popUpContents);
// initialize pop up window
popupWindowDogs = popupWindowDogs();
// button on click listener
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShowDropDown:
// show the list view as dropdown
popupWindowDogs.showAsDropDown(v, -5, 0);
break;
}
}
};
// our button
buttonShowDropDown = (Button) findViewById(R.id.buttonShowDropDown);
buttonShowDropDown.setOnClickListener(handler);
}
public PopupWindow popupWindowDogs() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewDogs = new ListView(this);
// set our adapter and pass our pop up window contents
listViewDogs.setAdapter(dogsAdapter(popUpContents));
// set the item click listener
listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());
// some other visual settings
popupWindow.setFocusable(true);
popupWindow.setWidth(250);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// set the list view as pop up window content
popupWindow.setContentView(listViewDogs);
return popupWindow;
}
/*
* adapter where the list values will be set
*/
private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String[] itemArr = item.split("::");
String text = itemArr[0];
String id = itemArr[1];
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
return adapter;
}
}
DogsDropdownOnItemClickListener.java
public class DogsDropdownOnItemClickListener implements OnItemClickListener {
String TAG = "DogsDropdownOnItemClickListener.java";
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
// get the context and main activity to access variables
Context mContext = v.getContext();
MainActivity mainActivity = ((MainActivity) mContext);
// add some animation when a list item was clicked
Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
fadeInAnimation.setDuration(10);
v.startAnimation(fadeInAnimation);
// dismiss the pop up
mainActivity.popupWindowDogs.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
mainActivity.buttonShowDropDown.setText(selectedItemText);
// get the id
String selectedItemTag = ((TextView) v).getTag().toString();
Toast.makeText(mContext, "Dog ID is: " + selectedItemTag, Toast.LENGTH_SHORT).show();
}
}
Related
I'm trying to display a listview conatining clothes items ..the listview will appear after the button "enter" under edittext will be clicked ..thelistitems will be different depending on what is the string(colors) on edittext (PS: the string in Listview are name and refrence of clothes!)..
for exemple:
if user choses in edittext: "Color1, Color2, "
a list will appear with a name and refrence of clothes that contain those colors: "Item1, Item2"
Because Item1 and Item2 are the only ones to contain the color1 and color2!
The list of possible Items(clothes) are 100, and Possible input in edit text are 6 colors (Color1, Color2, Color3, Color4, Color5, Color6) ..every time the user choses a set of color, the list will be displayed with the possible Items than contain those colors! ( as explained here: https://i.imgur.com/XwHTmGY.png)
PS: i've already created a custom edittext and use the adapter with the different strings(Color1..Color6) and i know how to get the string from the edittext ..but how to create update the listview with different items w depending on the string(chosen colors) of the edittext is the priblem! Thanks!
How to that? i've searched on internet on similar exemples with no luck..
This is my code so far:
MainActivity.java
public class DecisionTree extends AppCompatActivity {
private static final String TAG = DecisionTree.class.getSimpleName();
TextView txt,txt2;
com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText editText;
String data;
private ListView listView;
private ItemAdapter itemListAdapter;
private List<Item> itemList = new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decision_tree);
/////////////////////////////////////////////////
listView = (ListView) findViewById(R.id.diseases_list_container);
itemListAdapter = new ItemAdapter(itemList, this);
listView.setAdapter(itemListAdapter);
listView.setFastScrollEnabled(true);
////////////////////////////////////////////////
// add some items
itemList.add(new Item("Jeans Refnum 2520"));
itemList.add(new Item("T shirt Refnum 1220"));
.
.
.
.
.
A long list of 100 items
//add new items and changes to adapter
itemListAdapter.notifyDataSetChanged();
////////////////////////////////////////////////
//Text
txt = (TextView) findViewById(R.id.textView);
txt2 = (TextView) findViewById(R.id.textView2);
txt.setText("Given a set of clinical features, this tool should provide you with a reasonable and relevant differential diagnsosis (not the definitive diagnosis!)");
txt2.setText("Remember, this tool adds to your diagnostic skills and serves as an educational aid. It is not meant to replace your clinical judgement.");
//the edittext
editText = (com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText) findViewById(R.id.auto_text_complete);
//Add some sample items
List<SampleItem> sampleItems = Arrays.asList(
new SampleItem("Blue"),
new SampleItem("Red"),
new SampleItem("Orange"),
new SampleItem("Yellow"),
new SampleItem("vert"),
new SampleItem("rouge")
);
editText.addAllItems(sampleItems);
//Get the ListView associated with the MultiSelectEditText
ListView list = editText.getListView();
//Add it to a FrameLayout somewhere in the activity
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
list.setLayoutParams(params);
final FrameLayout frame = (FrameLayout) findViewById(R.id.auto_list_container);
frame.addView(list);
// The output
//frameLayout = (FrameLayout) findViewById(R.id.auto_list_container2);
//Set a listener on bubble clicks
//editText.setBubbleClickListener(new com.mycardboarddreams.autocompletebubbletext.MultiSelectEditText.BubbleClickListener<SampleItem>() {
/* #Override
public void onClick(SampleItem item) {
//Log.d(TAG, "Item: " + item.getReadableName());
Toast.makeText(DecisionTree.this, item.getReadableName(),
Toast.LENGTH_LONG).show();
//displayListPatho();
}
});*/
//-----------------------------------------END ONCREATE
}
public void blahblah (View view) {
data= editText.getText().toString();
listView.setVisibility(View.VISIBLE);
Toast.makeText(DecisionTree.this, data,
Toast.LENGTH_LONG).show();
}
I acheived what i want with making this code:
1/ created a list with adapter
2/ on each click the items on adapter are removed( clearAdapter();) and new items are added (itemList.add(new Item("Jenny"));) depending on string from edit text( if (data.equals("Epistaxis, ")). and after the adapter is notified with itemListAdapter.notifyDataSetChanged();
Ps: blahblah (=Button OnClick) ..
public void blahblah (View view) {
data= editText.getText().toString();
if (data.equals("Epistaxis, ")){
clearAdapter();
itemList.add(new Item("Jenny"));
itemList.add(new Item("Bladna"));
itemList.add(new Item("Drafat"));
itemListAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
if (position == 0) {
Intent i=new Intent(DecisionTree.this, Figures.class);
startActivity(i);
} else if (position == 1) {
//code specific to 2nd list item
Toast.makeText(getApplicationContext(), "Place Your Second Option Code", Toast.LENGTH_SHORT).show();
} else if (position == 2) {
Toast.makeText(getApplicationContext(), "Place Your Third Option Code", Toast.LENGTH_SHORT).show();
}
}
}); }
else if (data.equals("Nasal Discharge, ")) {
clearAdapter();
itemList.add(new Item("Jenny2"));
itemList.add(new Item("Bladna2"));
itemList.add(new Item("Drafat2"));
itemListAdapter.notifyDataSetChanged();
}
Very long question, but it's not clear exactly what do you want?
If I understand right, you should do somthing like that:
Get your String string from EditText.
String[] items = string.split(" ");
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
What a problem with that?
I made my own dialog box class. This class has a button to delete an item from a listview(which is the main acctivity_main.xml). When I push the delete button the item does not get deleted.
I have seen this topic Android: how to remove an item from a listView and arrayAdapter. It just appears the user does not know how to get the item index correctly, which I believe I have done correctly.
Remove ListView items in Android This one is pretty close. But in my code I created my own dialog, this one is using a positive and negative button. I am passing variables between my dialog class and to the mainActivity.
my onClickListener in OnCreate withing the MainActivity
mFoodDataAdapter = new FoodDataAdapter();
final ListView listFoodData = (ListView) findViewById(R.id.listView);
listFoodData.setAdapter(mFoodDataAdapter);
//Handle clicks on the ListView
listFoodData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int whichItem, long id) {
FoodData tempFoodData = mFoodDataAdapter.getItem(whichItem);
//create a new dialog window
DialogShowFood dialog = new DialogShowFood();
// send in a reference to the note to be shown
dialog.sendFoodDataSelected(tempFoodData);
FoodDataAdapter adapter1 = new FoodDataAdapter();
/*this is where i send the data to the DialogShowFood.java*/
dialog.sendFoodDataAdapter(adapter1, whichItem);
// show the dialog window with the note in it
dialog.show(getFragmentManager(),"");
}
});
Here is my class for the dialog "DialogShowFood.java"
public class DialogShowFood extends DialogFragment {
FoodData mFood;
MainActivity.FoodDataAdapter mAdapter;
int mitemToDelete;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_show_food, null);
Button btnDelete = (Button) dialogView.findViewById(R.id.btnDelete);
builder.setView(dialogView).setMessage("Your food");
/*this sends the item to delete to the adapter*/
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapter.deleteFoodData(mitemToDelete);
dismiss();
}
});
return builder.create();
}
/*this gets the data to delete from the MainActivity*/
public void sendFoodDataAdapter(MainActivity.FoodDataAdapter adapter1, int whichItem) {
mAdapter = adapter1;
mitemToDelete = whichItem;
}
}
The function inside the adapter
/*this is the function in the base adapter to delete the item*/
public void deleteFoodData(int n){
Toast.makeText(MainActivity.this,Integer.toString(n), Toast.LENGTH_SHORT).show();
foodDataList.remove(n);
notifyDataSetChanged();
}
The Toast outputs the proper indexes of the item to delete, it just does not delete the item for some reason.
I have a ListView dynamically inflated with custom layout that has different text views and a button. On button click, a user specifies options in a dialog window and the data returned to the selected item in the list view.
I expect the data to get inserted in text views of the corresponding item in the list view. However, when the list has fewer item that are not scrollable, no data gets inserted at all when dialog is closed and when it has enough items to be scrollable, the data gets inserted into text views of wrong item in the list. I don't know what I am doing wrong, here is my code:
public double COST_EM = 0.00, COST = 0.00, NUM_CO = 0.00;
private Spinner mPSpinner, mMediSpinner;
private ArrayAdapter<String> pmedi, numCo;
private TextView mPTv, mCoTv, mSubMain, mSubTv;
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = null;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_custom_layout, parent, false);
// Display image in the ImageView widget
TempP tphoto = tempPList.get(position);
mPTv = (TextView) view.findViewById(R.id.p_tv_po);
mCoTv = (TextView) view.findViewById(R.id.co_tv_po);
mSubMain = (TextView) view.findViewById(R.id.sub_list);
mModify = (Button) view.findViewById(R.id.modify_btn_po);
mModify.setOnClickListener(new View.OnClickListener() {
// calculate the order cost
protected void calculateCost() {
mSub = ((COST_EM + COST) * NUM_CO);
mSubtv.setText("" + Double.toString(mSub));
}
#Override
public void onClick(View v) {
mDialog = new Dialog(PCustom.this);
mDialog.setContentView(R.layout.item_custom_dialog);
mDialog.setTitle("Modify specifications");
mPSpinner = (Spinner) mDialog.findViewById(R.id.ces_sp_dialog);
mSubTv = (TextView) mDialog.findViewById(R.id.sub_der_dialog);
// set spinner adapters (code truncated for brevity)
pmedi = new ArrayAdapter<String>(MyApplication
.getContext(), R.layout.spinner_style, pmedi);
mPSpinner.setAdapter(pmedi);
mPSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int pos, long arg3) {
if (mPSpinner.getSelectedItem() == "Glossy") {
COST = 2000.00;
} else if (mPSpinner
.getSelectedItem() == "Standard") {
COST = 1500.00;
} else if (mPSpinner
.getSelectedItem() == "Other") {
COST = 1000.00;
}
// calculate the cost
calculateCost();
}
public void onNothingSelected(
AdapterView<?> arg0) {
}
});
Button save = (Button) mDialog
.findViewById(R.id.save_btn_po_dialog);
Button cancel = (Button) mDialog
.findViewById(R.id.cancel_btn_po_dialog);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// String newnumber =
// mobileNumber.getText().toString();
mPTv.setText("" + mPSpinner
.getSelectedItem());
mCoTv.setText((String) mNCoSpinner
.getSelectedItem());
mSubMain.setText(Double.toString(mSub));
mDialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
mDialog.show();
}
});
return view;
}
The method getView() return one item View each time ListView call it with a specific "position" parameter, so the times it is called is no less than the number of items it has. So, your member variables mPTv, mCoTv and mSubMain will be reassigned many times and finally have their values in the final calling of getView().That's why you meet that problem.
To solve your problem, you need to have the correct TextViews when the "save Button" is clicked.Here is how to find those correct TextViews:
In the OnClickListener of mModify Button, the "v" parameter in the method onClick(View v) is the same instance of mModify itself. So, you can use it to find those correct TextViews. Perhaps you can set the item root View as its tag and get the root View in onClick(View v) and then use it to find all those correct TextViews. Here is how to change your code:
mModify = (Button) view.findViewById(R.id.modify_btn_po);
// set the root view as the tag of "modify button".
mModify.setTag(view);
mModify.setOnClickListener(new View.OnClickListener() {
// calculate the order cost
protected void calculateCost() {
mSub = ((COST_EM + COST) * NUM_CO);
mSubtv.setText("" + Double.toString(mSub));
}
#Override
public void onClick(View v) {
// retrieve the root view here, it's the root view of the item on which you
// clicked the "modify button".
View view = (View)v.getTag();
// find the correct TextViews here.
mPTv = (TextView) view.findViewById(R.id.p_tv_po);
mCoTv = (TextView) view.findViewById(R.id.co_tv_po);
mSubMain = (TextView) view.findViewById(R.id.sub_list);
BTW, you didn't optimize your ListView, so it may not scroll smoothly, but this is not what caused your problem.You can refer to this:
How to optimize Android ListView?
I have been attempting to add a footer button to the end of my list. My list is working appropriately however I cannot figure out why I cannot add the footer view. My end goal is to inflate the view and add a footer button via xml however I need to get this to work at least first.
public void onActivityCreated(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// storing string resources for users inventory into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
ListView lv = getListView();
// Binding Array to ListAdapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.inventory_list, R.id.label, adobe_products);
// LoadMore button
Button btnScan = new Button(getActivity());
btnScan.setText("Scan Inventory");
// Adding Load More button to list view at bottom
lv.addFooterView(btnScan);
this.setListAdapter(adapter);
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
//Intent i = new Intent(PhotosFragment.this, InventoryItem.class);
// sending data to new activity
//i.putExtra("product", product);
//startActivity(i);
}
});
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
//Intent send_Scan=new Intent(PhotosFragment.this, ScanActivity.class);
//PhotosFragment.this.startActivity(send_Scan);
}
});
}
Edit :
When running the application it seems to be stuck in an infinite loop. Consistently loading.
You can't get ListView in onCreateView.
Use in onStart():
#Override
public void onStart() {
super.onStart();
LayoutInflater inflater = getActivity().getLayoutInflater();
getListView().addFooterView(inflater.inflate(R.layout.ly_footer_acreditacao, null));
}
Practicing on the ListView, I thought of adding buttons as well to it, rather than showing only content. But in my implementation, the button does not do anything at all.
Plus I was confused whether I could get the position of the button clicked. For now I am just sending the toSend declared inside the OnItemClick in an intent.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
final int toSend = position;
TextView refId = (TextView)view.findViewById(R.id.list_id);
TextView refName = (TextView)view.findViewById(R.id.list_name);
TextView refAdd = (TextView)view.findViewById(R.id.list_address);
Button edit = (Button)view.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(ListActivity.this, EditLayout.class);
i.putExtra("position", toSend);
startActivity(i);
}
});
String sd_id = refId.getText().toString();
String sd_name = refName.getText().toString();
String sd_add = refAdd.getText().toString();
buildAlert(sd_id, sd_name, sd_add);
}
});
You're pretty close. The "inside" setOnClickListener needs to happen when you create the list row view (the view containing id, name, address, edit).
You can do that during getView(). But where to send the clicks? Instead of creating a new onClickListener, use "this" (your activity). Put an onClick() handler in the activity.
Then, when you get a click, the onClick method will execute. Next problem: how do you know which row clicked? The easiest way that comes to mind is to give the button a different id for e ach row - use the row index (you might need to start at 1 rather than 0 - be warned).
Finally, given the row id, it's easy to start your "nested" activity.
Hope this helps.
(added later)
I do it like this; you'll need to define a layout for your row view:
class MyActivity extends Activity implements View.OnClickListener
{
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.my_page);
ListView list = (ListView)findViewById (android.R.id.list);
MyArrayAdapter adapter = new MyArrayAdapter (this, <your array of data>);
list.setAdapter (adapter);
}
#Override
public void onClick(View v)
{
int buttonId = v.getId();
if (buttonId is within range)
... do what you need to do with the click ...
}
private class MyArrayAdapter extends ArrayAdapter<MyData>
{
private Activity act;
//-----------------------------------------------------------------------------
public MyArrayAdapter (Activity act, MyData array)
{
super (act, R.layout.list_row, array);
this.act = act;
}
//-----------------------------------------------------------------------------
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
ViewGroup rowView = (ViewGroup)convertView;
if (rowView == null)
{
LayoutInflater inflater = act.getLayoutInflater();
rowView = (ViewGroup) inflater.inflate (R.layout.list_row,
parent, false);
}
Button button = (Button)rowView.findViewById (R.id.is_member);
button.setId (position+1); // add one to avoid 0 as an id.
button.setOnClickListener (act);
// set field values here -- not shown
return rowView;
}
}
}