How to capture List Dialog result - Android - android

I am new to Android. I am stuck, need help.
I have a List as my Activity. OnItemLongClickListener for any element of a List, I am displaying a Dialog with Custom List (Red, Green, Blue) & on the selection of any of the items (Red, Green, Blue) I need to change the back color of the selected item (on which the event raised the Dialog) of a List (main activity).
The dialog box pops, but I am stuck how to get the selected item (of Dialog). Below is my code.
public class SimpleList extends ListActivity
{
String[] contactNames = {"Name 1", "Name 2", "Name 3", "Name 4", "Name 5", "Name 6"};
ArrayAdapter<String> contactAdpater;
String itemSelected;
String choosenColor;
private final Context context = this;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ArrayList<String> myContactList = new ArrayList<String>(Arrays.asList(contactNames));
OnItemLongClickListener itemChangeColorListener = new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View arg1, int position, long arg3) {
itemSelected = parent.getItemAtPosition(position).toString();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final String[] colorNames = {"Red","Green","Blue"};
builder.setTitle("Pick a Colour!")
.setItems(colorNames, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
choosenColor = colorNames[which];
//Toast.makeText(getApplicationContext(), colorNames[which], Toast.LENGTH_SHORT).show(); <<-- its working fine here
//I am not able to access parent here... I want to perform,
**//parent[position].setBackgroundColor(Color.RED); in case Red is selected from Dialog**
}
});
builder.show();
return false;
}
};
contactAdpater = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
myContactList);
setListAdapter(contactAdpater);
getListView().setOnItemLongClickListener(itemChangeColorListener);
}
}

Yes got your problem
You have to use view's setBackgroundColor(int color); for changing the color if selected item of first ListView with the color selelcted from Dialog.
So In onClick you must use :
choosenColor = colorNames[which];
if(choosenColor.equals("Red"))
{
view.setBackgroundColor(Color.RED);
}
else if(choosenColor.equals("Blue"))
{
view.setBackgroundColor(Color.BLUE);
}
else if(choosenColor.equals("Green"))
{
view.setBackgroundColor(Color.GREEN);
}

Related

How to delete item from ListView while using Custom ArrayAdapter w/ Dialog

Some Context: I have a Custom ArrayAdapter for a ListView that has 3 parameters Name, Edit Button, Delete Button. I have setup onClicks in the ArrayAdapter to be able to detect which profile is being clicked with the specific edit/delete button press. When the user deletes a profile I remove the profile from SQLite DB however now I've ran into the problem of trying to update the ArrayList with the removed item and notifyDataSetChanged for my ListView.
Question 1: I can't figure out if I should be doing this in the Class that is containing the ListView and ArrayList or if I should be trying to update this from the ArrayAdapter in the onClicks.
Question 2: Whatever method might be right how can I correctly update the deleted item from the ListView when the user confirms the delete in the Dialog.
Current ArrayAdapter Class
public class ListViewItemAdapter extends ArrayAdapter<ListViewItem>
{
private Context mContext;
private List<ListViewItem> list = new ArrayList<>();
private DatabaseHelper databaseHelper;
private String profileName;
public ListViewItemAdapter(#NonNull Context context, ArrayList<ListViewItem> listItem) {
super(context, 0 , listItem);
mContext = context;
list = listItem;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.custom_listview,parent,false);
final ListViewItem listViewItem = list.get(position);
//Text View Profile
final TextView name = (TextView) listItem.findViewById(R.id.textView_name);
name.setText(listViewItem.getmName());
profileName = listViewItem.getmName();
//Edit Button Profile
ImageButton image = listItem.findViewById(R.id.imageView_poster);
image.setImageResource(listViewItem.getmImageDrawable());
image.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(mContext,
"Edit Profile:" + listViewItem.getmProfile() + " Name:" + listViewItem.getmName(),
Toast.LENGTH_SHORT).show();
}
});
//Delete Button Profile **Currently Testing**
ImageButton image2 = listItem.findViewById(R.id.imageView_poster2);
image2.setImageResource(listViewItem.getmImageDrawable2());
image2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
databaseHelper = new DatabaseHelper(getContext());
Toast.makeText(mContext,
"Delete Profile:" + listViewItem.getmProfile() + " Name:" + listViewItem.getmName(),
Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(),R.style.AlertDialogTheme);
builder.setTitle("Delete Profile?")
.setMessage("Are you sure you want to delete\n" + listViewItem.getmName())
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteRowProfile(listViewItem.getmName());
//
//This is where I'm try to update the ListView
//
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
});
return listItem;
}
}
Function in Fragment Class that Populates the ListView onViewCreated
public void getProfileList()
{
arrayList = new ArrayList<ListViewItemAdapter>();
listViewItemAdapter = new ListViewItemAdapter(getContext(),arrayList);
Cursor result = databaseHelper.getAllDataCarProfile();
if(listViewItemAdapter != null){
listViewItemAdapter.clear();
listViewItemAdapter.notifyDataSetChanged();
}
if (result.getCount() != 0)
{
while (result.moveToNext())
{
arrayList.add(new ListViewItem("CarProfile",
result.getString(0),
R.drawable.ic_edit_gray_24dp,
R.drawable.ic_delete_grey_24dp));
}
listViewItemAdapter.notifyDataSetChanged();
}
listViewCarProfile.setAdapter(listViewItemAdapter);
}
You can do this in either way . You can create a function in your adapter class and perform the clickListener on it .
deleteItem.setOnClickListener(v -> {
potsList.remove(getAdapterPosition());
notifyDataSetChanged();
}
Or in your class , when remove the item from list , don't forget to notify the adapter . One the adapter get notified , it will reflect the change on screen.

Android spinner - always select index 0

I have a spinner in my layout and I would like to select only first option (index 0) no matter user selection have been made. I have some code, but there is some text flicker when spinner change rapidly from user selection to index 0. So I would like to make no user selection / select index 0 at first.
This is my code:
final Spinner onespinner = (Spinner) findViewById(R.id.spinner0);
String[] items0 = new String[] { "item 1", "item 2", "item 3","item 4","item 5" };
ArrayAdapter<String> adapter0 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, items0);
onespinner.setAdapter(adapter0);
onespinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// automaticaly select first option
onespinner.setSelection(0,true);
// but there is some text flicker
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});

AlertDialog - do not dismiss on item click

OK so I am creating an ArrayAdapter and using it in my Alert Dialog because I don't want to show the default radio buttons on SingleItemSelection dialog.
Instead I want to change the background of the item that is selected, and then when the user presses the positive button I will perform the action related to the item that has been selected.
private void showAlertDialog()
{
final String[] options = getResources().getStringArray(R.array.dialog_options);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, options);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("My Dialog");
dialogBuilder.setAdapter(adapter, new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "item clicked at index " + which, Toast.LENGTH_LONG).show();
// Here I need to change the background color of the item selected and prevent the dialog from being dismissed
}
});
//String strOkay = getString(R.string.okay);
dialogBuilder.setPositiveButton("OK", null); // TODO
dialogBuilder.setNegativeButton("Cancel", null); // nothing simply dismiss
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
There are two problems I'm trying to tackle.
How do I prevent the dialog from being dismissed when the user clicks on an item
How do I change the background of the item that has been selected when the user clicks on it
To prevent dialog from dismissing on item click you can use AdapterView.OnItemClickListener instead of DialogInterface.OnClickListener.
Like this:
dialogBuilder.setAdapter(adapter, null);
...
AlertDialog dialog = dialogBuilder.create();
alertDialog.getListView().setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do your stuff here
}
});
You can set custom ListView as content of AlertDialog and set OnItemClickListener
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String[] items = ...;
ListView list = new ListView(this);
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, items));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos, long id) {
...
}
});
builder.setView(list);
and then save reference to dialog
mDialog = builder.show();
in order to dismiss it if necessary
mDialog.dismiss();
How do I prevent the dialog from being dismissed when the user clicks on an item
How do I change the background of the item that has been selected when the user clicks on it
Here is example
public class MainActivity extends AppCompatActivity {
private static final String listFragmentTag = "listFragmentTag";
private static final String data[] = {"one", "two", "three", "four"};
public MainActivity() {
super();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnClick(View v) {
ListFragment lf = new ListFragment();
lf.show(getSupportFragmentManager(), listFragmentTag);
}
public static class ListFragment extends DialogFragment {
#Override #NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
adb.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("List")
.setItems(data, null)
.setPositiveButton("OK", null); // pass your onClickListener instead of null
// to keep dialog open after click on item
AlertDialog ad = adb.create();
ad.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
private int colorOrg = 0x00000000;
private int colorSelected = 0xFF00FF00;
private View previousView;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// restoring color of previous view
if(previousView != null) {
previousView.setBackgroundColor(colorOrg);
}
// changing items's BG color
view.setBackgroundColor(colorSelected);
previousView = view;
}
});
return ad;
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
}
}
}
You can use setCanceledOnTouchOutside(false) or setCanceleable(false).
Set selector for the root element tag of the dialog layout xml.

Double Spinner for Android

I'm new to this forum, but i came here because i need some help with some spinners i'm trying to create for an Android app.
I have created 1 spinner and that works fine, but now i want to add a second spinner and i want the if statement i have to work depending on the two selections of the spinners.
For example, if item 1 is selected on spinner 1 and item 3 is selected on spinner 2 then do the if statement.
But i don't know how to get that to work. could anyone help me please.
This is the code i have now for 1 spinner:
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.weight_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
public class MyOnItemSelectedListener implements OnItemSelectedListener
{
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id)
{
final String itemSelected = parent.getItemAtPosition(pos).toString();
if (valueEntered.getText().length() == 0)
{
valueEntered.setText(String.valueOf(0));
}
if (itemSelected.equals("Stones"))
{
float valueInput = Float.parseFloat(valueEntered.getText().toString());
Toast.makeText(parent.getContext(), "The scale is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
valueEntered.setText(String.valueOf(convertSToK(valueInput)));
}
}
I really need some help, many thanks,
Davide Sousa
Use a dialog like the spinner:
private Dialog b1()
{
final String[] items = {
"Item 1",
"Item2",};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hi this is a spinner"));
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item) {
case 0:{
/* Item 1 */ break;}
case 1:{
/* Item 2 */break;}
}
}
});
return builder.create();
}
and then show the dialog with b1().show();

Acess AdapterView from Dialog

I have my ListActivity that when you tap on an item, it pops up a Dialog that ask the user for user and password. How can I get the selected position from the dialog?
Here's how I initialize the ListActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
showDialog(DIALOG_USER_PASSWORD);
}
});
}
The Dialog I pop up is a simple AlertDialog with 2 EditText which I inflate from an xml file
protected Dialog onCreateDialog(int id) {
switch (id) {
...
case DIALOG_USER_PASSWORD:
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(MyListActivity.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.ask_user_password)
.setView(dialogView)
.setPositiveButton(R.string.ok_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String userName = ((EditText) findViewById(R.id.username_edit_alert_dialog))
.getText().toString();
String password = ((EditText) findViewById(R.id.password_edit_alert_dialog))
.getText().toString();
Credentials cred = new CredentialsL1(userName, password);
/* HERE IS WHERE i NEED THE SELECTED ITEM
mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
mService.connect(mId, cred);
}
})
// Cancel button
.setNegativeButton(R.string.cancel_text,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
})
.create();
}
return null;
}
The only I've come up with is creating a new field "mId" and setting it when the user taps and using it when the user taps OK in the Dialog. Any more elegant idea?
Thanks
private int selectedPosition;
...
protected void onCreate(Bundle savedInstanceState) {
....
// inside the item listener...
selectedPosition = position;
showDialog(DIALOG_USER_PASSWORD);
/* HERE IS WHERE i NEED THE SELECTED ITEM
mId IS THE OBJECT ASSOCIATED TO THE SELECTED POSITION */
// just use selectedPosition var
Any more elegant idea?
It seems that you use a normal ListView (not a checkbox one)... so, it's fine to do it this way.

Categories

Resources