popup menu for spinner in android - android

i want a spinner with items'A','B','C'
if u select 'A' or'B' means the chronometer has to run.
while select the item 'C' the popup window has 2 open with edittext and 'Ok' button..
if you type the'D' in the edittext means that has too add in the spinner while add the chonometer has to run
here is my code:
public class Starttracker extends Activity {
PopupWindow popupWindow;
String[] Items = {
"A",
"B",
"C",
"D",
};
Spinner s1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
s1 = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item,Items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = s1.getSelectedItemPosition();
Toast.makeText(getBaseContext(),
"You have selected item : " + Items[index],
Toast.LENGTH_SHORT).show();
if (index==3)
{
LayoutInflater inflater = (LayoutInflater) Starttracker.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
popupWindow = new PopupWindow(inflater.inflate(R.layout.popup,null, false),300,100,true);
// RelativeLayout01 is Main Activity Root Layout
popupWindow.showAtLocation(findViewById(R.id.relativelayout), Gravity.CENTER, 0,0);
} else
{
Chronometer chrono=(Chronometer)findViewById(R.id.chronometer);
chrono.start();
}
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
can any help to me

final String[] items = {"A", "B", "C"};
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose me!");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if ("A".equals(items[item]) || "B".equals(items[item])) {
// run whatever...
}
if ("C".equals(items[item])) {
final EditText edit = new EditText(context);
final Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose a custom option.");
builder.setView(edit);
builder.setPositiveButton("Save", new OnClickListener() {
public void onClick(final DialogInterface dialog, final int which) {
String input = edit.getText().toString();
// add input to array, or do whatever.
dialog.dismiss();
}
});
builder.create().show();
}
dialog.dismiss();
}
});
builder.create().show();
I didn't test it (written straight from my mind), but it should work with a few modifications.
Good luck
Tom

TRy this code..
public class Starttracker extends Activity {
String[] Items = {
"A",
"B",
"C",
"D",
};
Spinner s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
s1 = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item,Items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
}
public boolean onItemSelected(AdapterView parent,View v, int position, long id) {
if (((items[position])=="A")||((items[position])=="B")) {
Chronometer chrono=(Chronometer)findViewById(R.id.chronometer);
chrono.start();
}
}
//.....
GoodLuck

the answer is following to my question:
{
int size=tempArray.length;
for(int i=0;i<size;i++){
Items.add(tempArray[i]);
}
and
if(index==3)
{
final Dialog dialog=new Dialog(Starttracker.this);
dialog.setContentView(R.layout.popup);
dialog.setTitle("Enter The Item");
dialog.setCanceledOnTouchOutside(true);
final EditText filename=(EditText)dialog.findViewById(R.id.filename);
filename.setText("");
Button d_ok=(Button)dialog.findViewById(R.id.d_ok);
Button d_cancel=(Button)dialog.findViewById(R.id.d_cancel);
d_ok.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
String textHolder = filename.getText().toString();
dialog.dismiss();
Items.add(textHolder);
// s1.setAdapter(adapter);
// notifyDataSetChanged();
}
});
d_cancel.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v,MotionEvent me){
dialog.dismiss();
return false;
}
});
dialog.show();
return;
}
thank a lot to all

Shameless plug for my project.
Check out Android Popup Spinner View

Related

Second AlertDialog list item click based on the first Alertdialog list android

In my android app, I need to generate one Alertdialog with a list of Company name. For example Company 1, Company 2, Company 3. Now if the user cllick company 1, he will get second alertdialog which will show some actions. Like Phone Call, Email, etc. Now I have implemented this two alertdialog in my code. But what I want to do, that for each company there should be different Phone number and email adress. So Far I have tried with same number with all the company. But in real in real if user click company 1, he will get the second alert list of action with phone call, email. if he clicks phone option he will see the phone number company 1, if he clicks company 2, he will get alertoption with phone number of company 2. But I am very new in developing area. I know there is something with Mapping topic, by which I can do it easily but I am not getting actually how to proceed with it. My code is like this
public List<CompanyDetail> setCompanydata(){
int n = 3;
private List<CompanyDetail> companyDetailList = new ArrayList<CompanyDetail>(); //modifier private is not allowed here
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>(); //modifier private is not allowed here
for(int i=0;i<n;i++){
private CompanyDetail comD= new CompanyDetail(); //modifier private is not allowed here
comD.setcompanyPhoneNo(companyPhoneno); //cannot resolve problem companyPhone
comD.setcompanyEmail(compnayEmailId);
companyDetailList.add(comD);
companyContactDetail.add(companyname, companyDetailList);//cannot resolve method 'add(?,java util list..
}
return companyContactDetail; //incompatible type
}
private List<CompanyDetail> companyDetailList;
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>();
companyContactDetail = setCompanydata(); //unknown class company contact deatil
private void showFirstDialogwithList() {
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
builder.setCancelable(true);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("Contact");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.company_name);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this.getActivity(), R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(arrayAdapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
showSecondDialogwithList();
}
if (itemPosition == 1) {
alert.dismiss();
showSecondDialogwithList();
}
if (itemPosition == 2) {
alert.dismiss();
showSecondDialogwithList();
}
}
});
}
private void showSecondDialogwithList() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("+1234667");
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if(isPermissionGranted()){
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
My string arrays are
<string-array name="company_name">
<item>company 1</item>
<item>Company 2</item>
<item>Company 3</item>
</string-array>
<!-- AlertDialog way of Contact array -->
<string-array name="contact_way">
<item>Phone Call</item>
<item>Email</item>
</string-array>
<String-array name="phone">
<item>123456</item>
<item>125658</item>
<item>123451</item>
</String-array>
<String-array name="email">
<item>email1</item>
<item>email2</item>
<item>email2</item>
</String-array>
you can pass the position for the item and test it at your function or you can pass it directly :
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alert.dismiss();
showSecondDialogwithList(position);
}
private void showSecondDialogwithList(int position) {
String phoneNumber;
switch (position) {
case 1:
phoneNumber = "123";
break;
case 2:
phoneNumber = "456";
break;
case 3:
phoneNumber = "789"
}
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("+1234667");
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if (isPermissionGranted()) {
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
To go deep in to logic behind that kind of scenario best way to use *HashMap*.
according to your scenario. i change in your code check it out:
public class CompanyDetail{
String companyPhoneNo;
String companyEmail;
public void setcompanyPhoneNo(String phoneNo){
this.companyPhoneNo = phoneNo;
}
public void setcompanyEmail(String Email){
this.companyEmail = Email;
}
public String getcompanyPhoneNo(){
return companyPhoneNo;
}
public String getcompanyEmail(){
return companyEmail;
}
}
public HashMap<String, List<CompanyDetail>> setCompanydata(){
int n = 3;
private List<CompanyDetail> companyDetailList = new ArrayList<CompanyDetail>();
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>();
for(int i=0;i<n;i++){
CompanyDetail comD= new CompanyDetail();
comD.setcompanyPhoneNo(companyPhoneno);
comD.setcompanyEmail(compnayEmailId);
companyDetailList.add(comD);
companyContactDetail.add(companyname, companyDetailList);
}
return companyContactDetail;
}
private List<CompanyDetail> companyDetailList;
private HashMap<String, List<CompanyDetail>> companyContactDetail;
companyContactDetail = setCompanydata();
private void showFirstDialogwithList() {
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
builder.setCancelable(true);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("Contact");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.company_name);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this.getActivity(), R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(arrayAdapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
}
if (itemPosition == 1) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
showSecondDialogwithList();
}
if (itemPosition == 2) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
showSecondDialogwithList();
}
}
});
}
private void showSecondDialogwithList( String companyName, List<CompanyDetail> companyDetail) {
CompanyDetail obj = companyDetail.get(0);
private String companyPhone = obj.getcompanyPhoneNo();
private String companyEmail = obj.getcompanyEmail();
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(companyPhone);
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if(isPermissionGranted()){
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
It's not a good practice to display two dialogs one by one. Of course you can implement it, like described above, but it will be much better to display separated activity(fragment) with the list(ListView, RecyclerView) of companies and click on each item will show the dialog with needed params. It will look better from design side and users experience.

Android - spinner position value

Im using a Spinner in an AlertDialog as a Filter. When I reopen the Dialog after selecting an item, I want to select the chosen item from before by default. But some kind of magic is happening and I cant understand why the spinner is selecting the wrong item. The item list for the spinner is a String array with numbers from 4 to 42. {"4","6",.."42"}
When I select the first item "4" the position should be 0 and when I reopen the Dialog the exact item should be displayed. But instead it displays the item "10" on position 4.
Code Dialogfragment:
public class FittingSelectionDialogFragment extends DialogFragment {
private String dTitle;
private String[] list;
private int position;
private String filterItem;
private List<String> chosenFilterItems;
public interface FittingSelectionDialogListener {
public void onChosenDialogItem(String filterStrings,int menuPosition);
}
FittingSelectionDialogListener mListener;
public Dialog onCreateDialog(Bundle savedInstanceState){
final Spinner spinner2 = new Spinner(getActivity());
final TextView label = new TextView(getActivity());
final TextView label2 = new TextView(getActivity());
LinearLayout layout = new LinearLayout(getActivity());
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setGravity(Gravity.CENTER);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getContext(), R.layout.support_simple_spinner_dropdown_item, list);
spinner2.setAdapter(adapter2);
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
}
else{
spinner2.setSelection(Integer.valueOf(chosenFilterItems.get(position)));
}
label.setText("Rohr AD:");
label.setTextColor(getResources().getColor(R.color.colorParkerBlack2));
label.setTextSize(16);
label.setPadding(60,0,40,0);
label2.setText("mm");
label2.setTextSize(16);
label2.setTextColor(getResources().getColor(R.color.colorParkerBlack2));
dialog.setTitle(getdTitle());
layout.addView(label);
layout.addView(spinner2);
layout.addView(label2);
dialog.setView(layout);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int spinner2Position, long id) {
filterItem = list[spinner2Position];
chosenFilterItems.set(position,String.valueOf(spinner2Position));
Toast.makeText(getContext(),chosenFilterItems.get(position),Toast.LENGTH_SHORT).show(); //correct value
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
dialog.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onChosenDialogItem(filterItem,position);
Toast.makeText(getContext(),chosenFilterItems.get(position),Toast.LENGTH_SHORT).show();//wrong value
dismiss();
}
});
dialog.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
filterItem = "";
chosenFilterItems.set(position,"");
mListener.onChosenDialogItem(filterItem, position);
}
});
return dialog.create();
}
}
I made two Toasts inside the Listeners. The crazy thing is that in the OnItemSelectedListener the correct position value is displayed. In the PositiveButton OnClickListener is displaying the wrong value. Have you any idea?
I made a workaround by myself. I did not found the mistake by debugging. So I dont work with the position. I use the value to reselect the chosen Item. Not the best way, but works for this small itemlist.
Code:
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
}
else{
for(int i=0; i<list.length;i++){
if(list[i].equals(chosenFilterItems.get(position))){
spinner2.setSelection(i);
}
}
}
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int spinner2Position, long id) {
filterItem = list[spinner2Position];
}
dialog.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
chosenFilterItems.set(position,filterItem);
mListener.onChosenDialogItem(filterItem,position);
dismiss();
}
});
Use Handler and add some delay
int delay = 1000;
runOnUiThread (new Runnable () {
#Override
public void run () {
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
} else {
Integer.valueOf(chosenFilterItems.get(position)));
}
}
}, delay);

Remove item from another activity using button

The problem: I want to remove a item from my listview using a button in another activity.
I have tried several kinds of code, but it just doesn't seem to work.
Right know I use serializable to bundle the object to the other activity.
But I don't know how to remove it, from the other activity.
Can anybody help me with that?
Can I use the button from the second activity, in the first activity to delete the item from the listview?
Class A where I got my ListView
public class ListActivity extends Activity {
ListView list;
Button exit;
SimpleAdapter adapter;
final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override``
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
for (int i = 0; i < title.length; i++) {
Map<String, String> datalist = new HashMap<String, String>();
datalist.put("title", title[i]);
datalist.put("subtitle", subtitle[i]);
data.add(datalist);
}
// getDataInList();
adapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2, new String[] { "title",
"subtitle" }, new int[] { android.R.id.text1,
android.R.id.text2 });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
Class B where I got my accept button.
When I click accept, the item from the listview in Class A should be removed.
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
int requestCode = 1;
SimpleAdapter adapter;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});``
//Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You should not directly remove the item from the view, but from the data displayed in it.
For example if your ListView is displaying items from an ArrayList, just remove the item in the ArrayList from you Activity B, and call myAdapter.notifyDataSetChanged() when back in the Activity A, which contains the adapter.
You can remove items by accessing to the ArrayList or by overriding the remove() method if you have only access to the adapter (assuming your adapter extends ArrayAdapter).
Also, you may have to override usefull Adapter methods like getCount(), getView()...
Thanks to all.
I found another solution thanks to remove row from another activity
Class A
public class ListActivity extends Activity {
ListView list;
Button exit;
static List<ListItems> items = new ArrayList<ListItems>();
public static int deletePos;
static ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
list = (ListView) findViewById(R.id.list);
exit = (Button) findViewById(R.id.btnExit);
// Registration numbers
final String[] title = new String[] { "XMT 123", "KLE 456", "CKL 789",
"MRP 012", "DSV 345" };
// Name of the truck drivers
final String[] subtitle = new String[] { "Peter Lund", "Hans Larsson",
"Erik Petersson", "Bjørn Lundal", "Lars Svensson" };
items = new ArrayList<ListItems>();
for (int i = 0; i < title.length; i++) {
ListItems s = new ListItems(title[i], subtitle[i]);
items.add(s);
}
adapter = new ListAdapter(this, android.R.layout.simple_list_item_2,
items);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Intent intent = new Intent(ListActivity.this,
InformationActivity.class);
intent.putExtra("updateReg", title[position].toString());
intent.putExtra("updateName", subtitle[position].toString());
deletePos = position;
adapter.notifyDataSetChanged();
startActivity(intent);
}
});
exit.setOnClickListener(new OnClickListener() {
// Closes the application
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
Class B
public class InformationActivity extends Activity {
TextView name;
TextView reg;
TextView product;
TextView productNo;
Button accept;
Button edit;
Button exit;
AlertDialog dialog;
ListView list;
String result;
EditText search;
Context context = InformationActivity.this;
ArrayList<Materials> materialList = new ArrayList<Materials>();
// Materials
final static String[] material = new String[] { "Betong", "Grus", "Järn",
"Metall", "Grus fin", "Grus grov", "Sten" };
// Material numbers
final static String[] materialNo = new String[] { "123", "234", "345",
"456", "567", "789", "012" };
private void getDataInList() {
for (int i = 0; i < 7; i++) {
Materials mats = new Materials(result, result);
mats.setMaterialName(material[i]);
// mats.setMaterialNo(material[i]);
materialList.add(mats);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
name = (TextView) findViewById(R.id.name);
reg = (TextView) findViewById(R.id.reg);
product = (TextView) findViewById(R.id.product);
productNo = (TextView) findViewById(R.id.productNo);
accept = (Button) findViewById(R.id.btnAccept);
edit = (Button) findViewById(R.id.btnEdit);
list = (ListView) findViewById(R.id.list);
Bundle extras = getIntent().getExtras();
String selected_item = extras.getString("updateReg");
reg = (TextView) findViewById(R.id.reg);
reg.setText(selected_item);
Bundle extras1 = getIntent().getExtras();
String selected_item1 = extras1.getString("updateName");
name = (TextView) findViewById(R.id.name);
name.setText(selected_item1);
getDataInList();
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder popup = new AlertDialog.Builder(
InformationActivity.this);
popup.setTitle("Välj ny artikel");
// Search field
final EditText search = new EditText(context);
popup.setView(search);
search.setHint("Sök här...");
popup.setSingleChoiceItems(material, -1,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
materialList.get(which);
Toast.makeText(getApplicationContext(),
material[which], Toast.LENGTH_SHORT)
.show();
result = material[which];
}
});
// PositiveButton, updates the material info field.
popup.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
product.setText(result);
}
});
// NegativeButton, closes the pop-up.
popup.setNegativeButton("Avbryt",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
dialog = popup.create();
dialog.show();
}
});
// Remove item
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int deletePos = ListActivity.deletePos;
ListActivity.items.remove(deletePos);
ListActivity.adapter.notifyDataSetChanged();
finish();
}
});
}
}

Change Value Of ListItem onItemClick

I want to change the value of listItem when that listItem is clicked. I have provided the code below.
public class MyListDialogExampleActivity extends Activity implements OnItemClickListener {
ListView myListView;
String itemString = null;
String [] listViewArray = new String[] {"ABC", "DEF", "GHI", "JKL"};
MyArrayAdapter listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myListView = (ListView) findViewById (R.id.myListView);
listAdapter = new MyArrayAdapter(this, R.layout.list_row, R.id.list_tv, listViewArray);
myListView.setAdapter(listAdapter);
myListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Log.d("onItemClick", arg2+"");
String str = showListDialog();
// i want to change the selected list item with String str
}
public String showListDialog () {
final CharSequence[] items = {"1", "2", "3", "4"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a number");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
itemString = items[item].toString();
}
});
AlertDialog alert = builder.create();
alert.show();
return itemString;
}
}
you need to use the parameters sent to you on the onItemClick , so that you take the i-th element in the array you've used , change its value , and in the end , notify the adapter that the data has changed by using notifyDatasetChanged.
You can't change arrays during runtime
So you have to use List (http://developer.android.com/reference/java/util/List.html)

DialogFragment with extra space below ListView

As you can see, below the bottom list element in my ListView, there is excess space I can't seem to be rid of. I've tried Relative and Linearlayout, both look like this. Here's the code:
public class ChooseDialog extends DialogFragment implements
DialogInterface.OnClickListener {
String URLhome;
String Title;
String type;
/* public static ChooseDialog newInstance() {
ChooseDialog dialog = new ChooseDialog();
Log.v("a", "shit runs");
Bundle bundle = new Bundle();
dialog.setArguments(bundle);
return dialog;
}*/
public ChooseDialog(String type) {
this.type = type;
}
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setCancelable(true);
int style = DialogFragment.STYLE_NORMAL, theme = 0;
setStyle(style, theme);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(type);
builder.setNegativeButton("Cancel", this);
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog, null);
builder.setView(dialogLayout);
final String[] items = {"Red", "Green", "Blue" };
builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.v("touched: ", items[which].toString());
}}
);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
And the code that launches the dialog:
public OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
showNationalityDialog();
}
};
private void showNationalityDialog() {
FragmentManager fm = getSupportFragmentManager();
ChooseDialog nationalityDialog = new ChooseDialog("Nationality");
nationalityDialog.show(fm, "fragment_edit_name");
}
I know this question never drew much attention, but I finally solved the problem.
By using the listview that I created in XML rather than setting the builder's adapter, I managed to get rid of all the excess space.
Here's what the new code looks like:
switch (editText.getId()) {
case (0) :
ListView list = (ListView) dialogLayout.findViewById(R.id.listView1);
list.setAdapter(new ArrayAdapter<String>(activity, R.layout.dialoglist,
activity.getResources().getStringArray(R.array.ageArray)));
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
editText.setText(activity.getResources().getStringArray(R.array.ageArray)[arg2]);
dismiss();
}
});
builder = (Integer.parseInt(android.os.Build.VERSION.SDK) < 11)? new AlertDialog.Builder(activity) :
new AlertDialog.Builder(activity, android.R.style.Theme_Translucent);
builder.setNegativeButton("Cancel", this);
builder.setView(dialogLayout);
return builder.create();
If you are setting a custom view on the alert dialog (via setView()) that ONLY has a ListView then you don't need to use a custom view. The builder will automatically add a ListView into the view if set adapter is called.
The extra space at the end of the list view is probably your custom view with no content.
For example:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AccountChooserListAdapter adapter = new AccountChooserListAdapter(getActivity(), R.layout.choose_account_list_item,
accountMetadataFactory.getAccountsAsList());
return new AlertDialog.Builder(getActivity())
.setCancelable(true)
.setTitle(getActivity().getString(R.string.title_add_account))
.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listener.onAddAccount(which);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
}

Categories

Resources