I am relatively new to android and I am stuck on this problem. I created a button which launches a Dialog. The AlertDialog (to be specific) then programatically create a listView and assign an adapter to it. Now the user can click on some of the elements and the textView elements in the ListView become red. I then store the elements that were clicked. Now, when I create a dialog again, the same texts that were clicked become white.
So my question is, how do I access the listView's elements beforehand so I can alter the colour of the items that were previously clicked.
this is the java code:
private void populateListView(String[] els) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.single_listview_item,R.id.txtitem, els);
list = new ListView(this);
list.setAdapter(adapter);
list.setOnItemClickListener( new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ViewGroup vg=(ViewGroup)view;
TextView txt=(TextView)vg.findViewById(R.id.txtitem);
if(!currentList.isSelected(position)) {
txt.setBackgroundResource(R.color.redPastel);
currentList.select(position);
}
else{
txt.setBackgroundResource(R.color.white);
currentList.unselect(position);
}
}
});
}
//the listener for the button
public void showDialogListView(View view){
String [] selection = {};
Button buttonUsed = null;
switch (view.getId()){
case R.id.cuisineButton:
selection = cuisines.getArray();
currentList = cuisines;
buttonUsed = (Button) findViewById(R.id.cuisineButton);
break;
case R.id.mealTimeButton:
selection = times.getArray();
currentList = times;
buttonUsed = (Button) findViewById(R.id.mealTimeButton);
break;
}
populateListView(selection);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
final Button finalButtonUsed = buttonUsed;
builder.setPositiveButton("Select",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finalButtonUsed.setText(currentList.getSelectionText());
}
});
builder.setNegativeButton("Cancel",null);
builder.setView(list);
AlertDialog dialog=builder.create();
dialog.show();
}
}
this is the layout of the single element XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtitem"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textSize="25sp"
android:gravity="center"
/>
</LinearLayout>
You can get listView item like as
lv_view_task.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,final int arg2,
long arg3) {
final View selectedView v = arg1 ; // Save selected view in final variable**
AlertDialog.Builder alert=new AlertDialog.Builder(ViewTask.this);
alert.setTitle("title stackoverflow");
alert.setIcon(R.drawable.ic_launcher);
alert.setPositiveButton("Fix",new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String str=lv_view_task.getItemAtPosition(arg2).toString();
Toast.makeText(getApplicationContext(), str,Toast.LENGTH_LONG).show();
//Access view object v here
TextView label=(TextView) v.findViewById(R.id.label);
String xyz = label.getText();
}
});
Related
I have a button and when I click that button my first custom grid view pops up as dialogue. When I click an item my second custom grid view pops up dismissing my first custom grid view. Now the problem is here, when I click an item in my second custom grid view nothing happens. My setOnItemClickListener() is not working there.I couldn't able to trace my problem where I have done wrong.
Showing my first grid view `
public void outletList() {
dialogOutlet = new Dialog(SelectCategory.this);
dialogOutlet.setContentView(R.layout.outlet_dialogue_grid);
dialogOutlet.setTitle("Select Outlet");
final GridView lv = (GridView) dialogOutlet.findViewById(R.id.gridOutletView);
oa = new OutletAdapter(this, ParseData.OutletList);
lv.setAdapter(oa);
outletFlag = 1;
lv.setOnItemClickListener(this);
dialogOutlet.show();
dialogOutlet.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
Showing second grid view `
public void billList() {
dialogueBill = new Dialog(SelectCategory.this);
dialogueBill.setContentView(R.layout.bill_dialogue_grid);
dialogueBill.setTitle("Select Bill");
final GridView bv = (GridView) dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
System.out.println("focusable "+bv.isFocusableInTouchMode());
System.out.println("focusable "+bv.findFocus());
System.out.println("Outlet Flag Bill List>>>>>>"+outletFlag);
bv.setOnItemClickListener(this);
dialogueBill.show();
dialogueBill.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
On Item Click
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
System.out.println("Outlet Flag inside Item Click>>>>>>"+outletFlag);
if(outletFlag!=1){
HashMap<String, String> out = BillAdapter.billData.get(pos);
String sel_bill = out.get(ParseData.KEY_BILL_NO);
System.out.println("Selected Bill>>>>>>"+sel_bill);
selected_bill = sel_bill;
Intent iii = new Intent(SelectCategory.this, FBHome.class);
startActivity(iii);
}
else{
HashMap<String, String> out = OutletAdapter.outletData.get(pos);
String sel_name = out.get(ParseData.KEY_NAME);
String sel_code = out.get(ParseData.KEY_CODE);
out_pos = pos;
selected_outlet = sel_code;
selected_outlet_name = sel_name;
dialogOutlet.dismiss();
outletFlag = 0;
new GetBillDetails().execute();
}
}
Thanks in advance :)
In your Gridview Layout if you are using Clickable Widgets like Button or an ImageButton Change it and try.
That is android does not recognize click events inside the Gridadpater views, so if you change that everything should work fine
You could try
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/darker_gray"
android:layout_width="90dp"
android:layout_height="90dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/bt_grid"
android:layout_width="wrap_content"
android:textColor="#android:color/white"
android:layout_height="wrap_content" />
</LinearLayout>
Try using Alert Dialog
private void showGridDialog() {
// Prepare grid view
final GridView bv = (GridView)
dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
bv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do something here
}
});
// Set grid view to alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(bv);
builder.setTitle("Goto");
builder.show();
}
I have a dialog box that works perfectly well when i use just the spinner, but returns a null pointer when i try to fetch a value from an edit Text to be used for calculation in the OK button.
below is my deliberations for your consideration
//the alert box
public boolean dialogValuessP1() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Arena.this);
alertDialogBuilder.setTitle("Connecting Options");
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = li.inflate(R.layout.option, null);
EditText connectionNumber = (EditText)findViewById(R.id.txtConnectedBy);
connectedV = Integer.parseInt(connectionNumber.getText().toString());
spinnercategory = (Spinner) dialogView.findViewById(R.id.viewSpin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnercategory.setAdapter(adapter);
spinnercategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
ConnectBY = spinnercategory.getItemAtPosition(arg2).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
alertDialogBuilder.setView(dialogView);
alertDialogBuilder.setPositiveButton("Connect",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (ConnectBY == "Single Score") {
scoreV = 1 * connectedV;
} else if (ConnectBY == "Double Score") {
scoreV = 2 * connectedV;
} else if (ConnectBY == "Tripple Score") {
scoreV = 3 * connectedV;
}
alert = true;
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the alert box and put a Toast to the user
dialog.cancel();
Toast.makeText(getApplicationContext(),
"Please choose Connection Pattern",
Toast.LENGTH_LONG).show();
// Arena.this.finish(); used to close the game
alert = false;
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return alert;
}
//the option.xml is the Xml file used
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingLeft="10dip" >
<Spinner
android:id="#+id/viewSpin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#array/category" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/connectwith" />
<EditText
android:id="#+id/txtConnectedBy"
android:layout_width="76dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
</LinearLayout>
Since the edittext is inside the alert dialog
try using
EditText connectionNumber =(EditText) dialogView .findViewById(R.id.txtConnectedBy);
and to retrive the value use
String edittextValue=connectionNumber.getText().toString()
I think you can achieve this functionality with a custom dialog functionality
final Dialog dialog = new Dialog(CustomDialog.this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog);
// Set dialog title
dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image and button
EdittText text = (EdittText ) dialog.findViewById(R.id.textDialog);
Spinner spinimage = (Spinner) dialog.findViewById(R.id.spinner);
//spinner details here
dialog.show();
Button ok= (Button) dialog.findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
String text = text.getText().toString();
//do something with the edittext value
}
});
please make a try and share your view
Thanks for the suggestions, i made the following changes to the code and was able to use both an edittext and a spinner in the same alertdialog
public boolean dialogValuessP1() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Connecting Options");
LayoutInflater li = LayoutInflater.from(context);
final View dialogView = li.inflate(R.layout.option, null);
final EditText input = (EditText) dialogView
.findViewById(R.id.txtConnectedBy);
spinnercategory = (Spinner) dialogView.findViewById(R.id.viewSpin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnercategory.setAdapter(adapter);
spinnercategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
position = arg2 + 1;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
alertDialogBuilder.setView(dialogView);
alertDialogBuilder.setPositiveButton("Connect",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
edittextValue = input.getText().toString();
connectedV = Integer.parseInt(edittextValue);
scoreV = position * connectedV;
playNext();
alert = true;
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the alert box and put a Toast to the user
dialog.cancel();
Toast.makeText(getBaseContext(),
"It is not your turn to Play",
Toast.LENGTH_LONG).show();
alert = false;
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
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.
I want to delete a row from my list view on click of "delete" button. My listview item has following things placed horizontally: TextView-1,TextView-2,TextView-3,ImageButton-delete button. Now when I click delete button, the row should be deleted from the view. Below is the adapter code;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = (View) v.getParent();
TextView tv = (TextView) view.findViewById(R.id.item_name);
String item = tv.getText().toString();
String tableno = mListItems.get(0).getTableNumber();
orderDetailsDB = new OrderDetailsDBAdapter(
getApplicationContext());
orderDetailsDB.deleteItem(item,tableno);
I tried by setting Individual textviews to blank but its not working.
holder.itemName.setText("");
holder.amount.setText("");
holder.quantity.setText("");
I read couple of posts and they suggest to remove item from my list(mListItems) and then do adapter.notifyDataSetChanged();. Problem is I am not using array adapter for populating list view but using Custom adapter, so unable to get the position for item to be deleted. Please advise. thanks.
First write below line in your adapter's getView method.
button.setTag(position)
in onClick method
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
yourarraylistObject.remove(position);
// your remaining code
notifyDataSetChanged();
}
Just use remove() to remove list item from the adapter
for your reference
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
What you can do in order to get the position that you want to delete is to pass that into your listener:
// inside custom adapter
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
.....
deleteButton.setOnClickListener(new MyClickListener(position);
}
private class MyClickListener implements OnClickListener
{
int position = -1;
public MyClickListener(final int position)
{
this.position = position;
}
#Override
public void onClick(View v) {
// do your delete code here
notifyDataSetChanged();
}
I am trying to create a AlertDialog with multiple choice option. I have tried with the setMultiChoiceItems but what i have is a ArrayList<Category> and not a CharSequence so i tried with the adapter.
The problem with setAdapter is that when i select one item it closes the dialog window. And what i want is to select the items and then hit the OK button to see what items where selected.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
ArrayAdapter<Category> catsAdapter = new ArrayAdapter<Category>(this, android.R.layout.select_dialog_multichoice,this.categories);
builder.setAdapter(catsAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}
});
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do something
}
});;
AlertDialog alert = builder.create();
alert.show();
Unfortunately, there doesn't seem to be an easy way to toggle on AlertDialog's multichoicemode without calling setMultiChoiceItems().
However, you can set an adapter, then turn on multichoice mode in the contained ListView itself.
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setAdapter(yourAdapter, null)
.setPositiveButton(getResources().getString(R.string.positive), null)
.setNegativeButton(getResources().getString(android.R.string.cancel), null)
.create();
dialog.getListView().setItemsCanFocus(false);
dialog.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
dialog.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Manage selected items here
System.out.println("clicked" + position);
CheckedTextView textView = (CheckedTextView) view;
if(textView.isChecked()) {
} else {
}
}
});
dialog.show();
this will stop ur dialog from disappearing after one selection.
AlertDialog alertDialog = builder.create();
ListView listView = alertDialog.getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
To get which items are selected , you need to plan your adapter accordingly.
see below code it may help you. i used this in my app.
public static ArrayList<String> Party_list_new = new ArrayList<String>();
ArrayList<String> party_multi_cheked = new ArrayList<String>();
public void show_alert() {
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.alert_);
dia.setTitle("Select File to import");
dia.setCancelable(true);
final ListView list_alert = (ListView) dia
.findViewById(R.id.alert_list);
list_alert.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_multiple_choice,
Party_list_new));
list_alert.setItemsCanFocus(false);
list_alert.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_alert.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
}
});
Button btn = (Button) dia.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SparseBooleanArray positions = list_alert
.getCheckedItemPositions();
int j = 0;
for (int k = 0; k < Party_list_new.size(); k++) {
if (positions.get(k)) {
party_multi_cheked.add("" + k);
}
}
dia.dismiss();
}
});
dia.show();
}
alert_list.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Party" />
<ListView
android:id="#+id/alert_list"
android:layout_width="match_parent" android:padding="5dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
make it right if it is correct.