How to create alertdialog in spinner - android

I want to create alertDialog in spinner selected item, and add an EditText inside of alertDialog.
Thanks
sh = (Spinner) view.findViewById(R.id.shield);
ArrayAdapter<CharSequence> adaptera = ArrayAdapter.createFromResource(getActivity(),
R.array.shield, android.R.layout.simple_spinner_item);
adaptera.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sh.setAdapter(adaptera);
sh.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
sa = (String) sh.getSelectedItem();
AlertDialog.Builder alertDialogBuildera = new AlertDialog.Builder(getActivity());
alertDialogBuildera.setTitle("Your Title");
alertDialogBuildera
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
double sl = Double.valueOf(tc.getText().toString());
getActivity().finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialoga = alertDialogBuildera.create();
if (sa.trim().equals("Lead")) {
alertDialoga.show();
} else
if (sa.trim().equals("Steel")) {
alertDialoga.show();
}
}
});
it's doesn't work.
if I selected item, the alertdialog automaticaly shown.

Please check the below link.This will gives you detailed explanation on how to customize spinner. hope this will solves your problem.
http://mrbool.com/how-to-customize-spinner-in-android/28286
In that example you should replace imageview with edittext
Please use the below code i replaced imageview with edittext its working fine
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Spinner Customization"
android:textSize="30px" />
<Spinner
android:id="#+id/spinner_show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100px"
android:drawSelectorOnTop="true" />
custom_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="3px" >
<EditText
android:id="#+id/left_content"
android:layout_width="wrap_content"
android:layout_height="80px" />
<TextView
android:id="#+id/text_main_seen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5px"
android:layout_marginTop="2px"
android:layout_toRightOf="#+id/left_content"
android:padding="3px"
android:text="JMD Group"
android:textColor="#0022ee"
android:textSize="22px"
android:textStyle="bold" />
<TextView
android:id="#+id/sub_text_seen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_main_seen"
android:layout_marginLeft="5dip"
android:layout_toRightOf="#+id/left_content"
android:padding="2px"
android:text="beyond the expectations..."
android:textColor="#777777" />
</RelativeLayout>
MainActivity
public class MainActivity extends Activity {
String[] spinnerValues = { "Blur", "NFS", "Burnout", "GTA IV", "Racing", };
String[] spinnerSubs = { "Ultimate Game", "Need for Speed",
"Ulimate Racing", "Rockstar Games", "Thunder Bolt" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
mySpinner.setAdapter(new MyAdapter(this, R.layout.custom_spinner,
spinnerValues));
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent,
false);
TextView main_text = (TextView) mySpinner
.findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
EditText left_content = (EditText) mySpinner
.findViewById(R.id.left_content);
left_content.setHint("This is EditText:"+(position+1));
return mySpinner;
}
}
}
Thanks

Related

in Android Studio the Button in ListView does not work

I'm creating a shopping list similar to listonic app, but I'm stuck in listView, the button inside my listView does not read clicks but OnItemClickListener is working well. the objective is the user can save multiple shopping list for example grocery list, self-care list, etc. I have searched everywhere but did not find something that works.
here is the activity for the shopping list
private ArrayList<String> data = new ArrayList<String>();
private FloatingActionButton addList;
private ListView listView;
private TextView nList_name;
private DatabaseHelper dbHelper;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_lists);
dbHelper = new DatabaseHelper(this);
listView = findViewById(R.id.list_view);
addList = findViewById(R.id.add_list);
loadTaskList();
addList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add_item();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MyListsActivity.this, "list num "+position, Toast.LENGTH_SHORT).show();
}
});
}
private class MyListAdapter extends ArrayAdapter<String>
{
private final int layout;
public MyListAdapter(#NonNull Context context, int resource, #NonNull List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
final int pos = position;
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
viewHolder = new ViewHolder();
viewHolder.thumbnail = convertView.findViewById(R.id.list_item_thumbnail);
viewHolder.title = convertView.findViewById(R.id.list_item_text);
viewHolder.button = convertView.findViewById(R.id.list_item_btn);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.title.setText(getItem(position));
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MyListsActivity.this, "btn at row "+position, Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(viewHolder);
return convertView;
}
}
public static class ViewHolder
{
ImageView thumbnail;
TextView title;
Button button;
}
private void add_item()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MyListsActivity.this);
builder.setTitle("Add new list");
View v = LayoutInflater.from(MyListsActivity.this).inflate(R.layout.shop_list_dialog_item, null, false);
builder.setView(v);
TextInputEditText nList_name_edit_txt = v.findViewById(R.id.list_name_edit_txt);
TextInputLayout nList_name_layout = v.findViewById(R.id.list_name_layout);
builder.setPositiveButton("CREATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i){}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {dialogInterface.cancel();}
});
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String task = String.valueOf(nList_name_edit_txt.getText()).trim();
if (!TextUtils.isEmpty(nList_name_edit_txt.getText()))
{
dbHelper.insertNewTask(task);
loadTaskList();
dialog.cancel();
}
else{nList_name_layout.setError("Name your list");}
}
});
}
private void loadTaskList() {
ArrayList<String> taskList = dbHelper.getTaskList();
if(mAdapter==null){
mAdapter = new ArrayAdapter<String>(this, R.layout.list_wrapper_item, R.id.list_item_text, taskList);
listView.setAdapter(mAdapter);
}
else{
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
}
}
this is the xml for the shopping list activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyListsActivity">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/add_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24" />
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
and this is the layout for the adapter
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants">
<ImageView
android:id="#+id/list_item_thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_image_24" />
<TextView
android:id="#+id/list_item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp"
android:textColor="#color/youtube"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/list_item_thumbnail"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/list_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Your MyListAdapter works as it should except int position should be final int position because button calls it from inner class.
The problem is that you are not using MyListAdapter. So change
mAdapter = new ArrayAdapter<String>(this, R.layout.list_wrapper_item, R.id.list_item_text, taskList);
To
mAdapter = new MyListAdapter(this, R.layout.list_wrapper_item, taskList);

Using spinner in android fragment view and button click

I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_paternity"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:layout_marginTop="52dp"
android:id="#+id/paternity_ans" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="#+id/textView6"
android:text="Father"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_above="#+id/childblds"
android:layout_centerHorizontal="true" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="53dp"
android:id="#+id/textView5"
android:text="Child "
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/btn_paternity"
android:layout_toStartOf="#+id/btn_paternity" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
android:id="#+id/dadblds"
android:dropDownWidth="match_parent"
android:layout_toLeftOf="#+id/textView4"
android:layout_toStartOf="#+id/textView4"
android:layout_alignBottom="#+id/childblds"
android:layout_alignTop="#+id/childblds" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/childblds"
android:spinnerMode="dialog"
android:dropDownWidth="match_parent"
android:layout_marginTop="13dp"
android:layout_below="#+id/textView5"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/momblds"
android:spinnerMode="dialog"
android:entries="#array/paternitybldtype"
android:dropDownWidth="match_parent"
android:layout_alignTop="#+id/dadblds"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_paternity"
android:layout_below="#+id/dadblds"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:gravity="center_horizontal"
android:text="Mother"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginLeft="9dp"
android:layout_marginStart="9dp"
android:layout_above="#+id/childblds"
android:layout_toRightOf="#+id/textView6"
android:layout_toEndOf="#+id/textView6" />
</RelativeLayout>
</LinearLayout>
Fragments code:
public class Paternitytest extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Some if else statement will be applied here by using String c, f and m
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String f = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String m = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
I have made some changes in your code so try this.
public class Paternitytest extends Fragment {
private String childSpinnerString, momSpinnerString, dadspinnerString;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo,
container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Some if else statement will be applied here by using String c, f and m
Log.d("Blood groups- ", "Child - " + childSpinnerString + " Mom - " + momSpinnerString + " Dad - " + dadspinnerString);
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
childSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
dadspinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
momSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Try onClickListener for your button:
btn_paternity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String mom = momblds.getSelectedItem().toString();
}
});

How do calculate multiple spinner value with edit text?

Im new in android programing, I want make calculating with multiple spinner that have value string and edit text. and proccess with button click and show on text view. please healp me to fix so i can learn next subject.
THx
My activity .java code:
public class MainActivity extends Activity {
private EditText jumlah;
String[] spinnerValues = { "Bakso", "Es Buah" };
String[] spinnerSubs = {"10000", "8000" };
int total_images[] = { R.drawable.bakso, R.drawable.es_buah };
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner_show);
mySpinner.setAdapter(new MyAdapter(this, R.layout.menu_resto,
spinnerValues));
jumlah = (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
initButton();
}
private void initButton() {
button1.setOnClickListener(new OnClickListener() {
// this one performs an action when our button is clicked. it performs whatever is below
#Override
public void onClick(View v) {
// String strA = i want call the spinersubs value that chsoed. how ?
String strB = jumlah.getText().toString();
Double dblAnswer = doCalc(strA, strB);
TextView lblAnswer = (TextView) findViewById(R.id.lblAnswer);
// the disadvantage is that we can't do anything to it outside of this curly
// in general it's wasteful to use fields when you can suffice with local variable
String answer = String.valueOf(dblAnswer);
// we get our answer and turn it to a string.
lblAnswer.setText(answer);
// finally we set our result to the textView.
}
});
}
public double doCalc(String a, String b) {
double dblA = Double.parseDouble(a);
double dblB = Double.parseDouble(b);
return dblA * dblB;
}
class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.menu_resto, parent,
false);
TextView main_text = (TextView) mySpinner
.findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
ImageView left_icon = (ImageView) mySpinner
.findViewById(R.id.left_pic);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
Here my XML
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="X - Resto Menu"
android:textSize="30px" />
<Spinner
android:id="#+id/spinner_show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100px"
android:drawSelectorOnTop="true" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_show"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:text="Jumlah Pesanan" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:onClick="#string/hitung"
android:text="#string/pesan" />
<TextView
android:id="#+id/lblAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="" />
You need to implement CustomOnItemSelectedListener for Spinner like
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and then set this Listener to your Spinner like
mySpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
and in Button click you'll get a Spinner selected value like
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner : "+ String.valueOf(mySpinner.getSelectedItem())
,Toast.LENGTH_SHORT).show();
}
});
Go to this for Tutorial

ListView setOnItemClickListener doesn't response

i try to get selected item from ListView but i dont get any respone from my listener
I dont get any calls at my log from this code:
public void onItemSelected(AdapterView<?> spinnerReference,
View rowReference, int arg2, long arg3) {
chooseExercise = itemsList.getSelectedItem().toString();
Log.i("choosed", chooseExercise);
}
My adapter:
public void setItemList(String muscle)
{
if (muscle.equals("All"))
items = data.getAllExercies();
else
items = data.getMuscleEx(muscle);
ArrayAdapter<CharSequence> exerciseAdapter;
if (items == null || items.length < 1)
items = new String[] {};
exerciseAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, items)
{
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
String text = items[position];
TextView listItem = new TextView(AddWorkOutPage.this);
listItem.setBackground(getResources().getDrawable(R.drawable.shape_box));
listItem.setTextSize(18);
listItem.setText(text);
listItem.setPadding(10, 20, 0, 20);;
listItem.setTextColor(Color.BLACK);
return listItem;
}
};
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
searchItemField.setAdapter(exerciseAdapter);
itemsList.setAdapter(exerciseAdapter);
}
My listview object code:
public void addExerciseDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose exercise");
View prefView = View.inflate(this, R.layout.choose_from_list, null);
searchItemField = (AutoCompleteTextView) prefView.findViewById(R.id.searchItemField);
itemsList = (ListView) prefView.findViewById(R.id.itemsList);
searchItemField.setDropDownHeight(0);
searchItemField.addTextChangedListener(this);
setItemList(wantedMuscle);
itemsList.setOnItemClickListener(this);
builder.setPositiveButton("Choose selected", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Log.i("exercise choose", chooseExercise);
dialog.dismiss();
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.dismiss();
}
});
builder.setNeutralButton("filter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
createDialog();
}
});
builder.setView(prefView);
builder.show();
}
My dialog XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:descendantFocusability="beforeDescendants"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#android:drawable/ic_menu_search" />
<ListView
android:id="#+id/itemsList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/searchItemField"
android:descendantFocusability="beforeDescendants"
android:layout_marginTop="5sp" >
</ListView>
<AutoCompleteTextView
android:id="#+id/searchItemField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imageView1"
android:ems="10" >
<requestFocus />
</AutoCompleteTextView>
</RelativeLayout>
What Listener are you using exactly? The OnItemClickListener has a method onItemClick() instead of your onItemSelected(). I'm not sure if yours would work too, but this works:
ListView listview = (ListView) v.findViewById(R.id.itemsList);
listview.setAdapter(...);
listview.setOnItemClickListener(new MyOnItemClickListener());
And the OnItemClickListener as an inner class:
private class MyOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Object o = parent.getItemAtPosition(position);
}
}

ListView.onItemClick not working

My ListView in Activity:
ListView listView1 = (ListView) menu.findViewById(R.id.menuList);
String menuItems[] = new String[] { "My Wants", "Profile", "Notifications",
"Feedback", "Logout" };
listView1.setAdapter(new SideMenuAdapter(this, menuItems, listView1));
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 1) {
Intent intent = new Intent(FeedListViewActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
if (position == 0) {
showMyWants();
}
}
});
menu is :
menu = inflater.inflate(R.layout.horz_scroll_menu, null);
horz_scroll_menu.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/menu"
android:layout_width="1dp"
android:layout_height="1dp"
android:background="#FFFFFFFF"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FF000000"
android:text="Menu"
android:textColor="#FFFFFFFF"
android:gravity="center" />
<ListView
android:id="#+id/menuList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#FFFFFFFF"
android:scrollbars="none" >
</ListView>
</LinearLayout>
My SideMenuAdapter:
public class SideMenuAdapter extends BaseAdapter {
private static final int TYPE_MAX_COUNT = 2;
private static LayoutInflater inflater = null;
private Activity activity;
public ImageLoader imageLoader;
public static String[] values;
ListView myList;
public SideMenuAdapter(Activity a, String[] sa, ListView lv) {
values = sa;
activity = a;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myList = lv;
}
public int getCount() {
return values.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView mainText;
public TextView sideText;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View vi = convertView;
LayoutInflater inflater = activity.getLayoutInflater();
vi = inflater.inflate(R.layout.side_menu_list_item, null);
holder.mainText = (TextView) vi.findViewById(R.id.mainText_sideMenu);
holder.sideText = (TextView) vi.findViewById(R.id.sideText_sideMenu);
vi.setTag(holder);
holder.mainText = (TextView) vi.findViewById(R.id.mainText_sideMenu);
holder.sideText = (TextView) vi.findViewById(R.id.sideText_sideMenu);
holder.mainText.setText(values[position]);
if (position == 2) {
holder.sideText.setText("3");
holder.sideText.setBackgroundResource(R.drawable.orange);
}
return vi;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
}
My Xml for ListView items:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sideMenuListItem"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:padding="3dp" >
<TextView
android:id="#+id/sideText_sideMenu"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:gravity="center"
android:textSize="20dp"
android:padding="5dp" />
<TextView
android:id="#+id/mainText_sideMenu"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#id/sideText_sideMenu"
android:clickable="true"
android:gravity="left|center_vertical"
android:textSize="20dp"
android:padding="5dp" />
</RelativeLayout>
when running this application on Emulator, if i click with mouse nothing happens. But when i select any item on the list using navigation buttons on the KeyBoard and click Enter, it works fine.
when running the app on a device. If i go on click any item of the list, like some 10-20 times it works sometimes.
Edit:
Actually everything worked fine when i was using predefined ArrayAdapter<String> and android.R.simple_list_item. But i want a custom adapter
why is it so?
Its because in my ListView item layout i added
android:clickable="true"
for both the TextViews. So when i click on the ListView item it indeed is a click on these TextView whose onClick is not implemented. Removing the clickable attribute from the TextViews solved my problem.
Thanks everyone
Try making the RelativeLayout clickable and focusable.
Layout File
<ListView android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000fff"
android:layout_weight="2"
android:drawSelectorOnTop="false">
</ListView>
Main Activity
public class MyListView extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, PENS));
getListView().setTextFilterEnabled(true);
}
static final String[] PENS = new String[]{
"MONT Blanc",
"Gucci",
"Parker",
"Sailor",
"Porsche Design",
"Rotring",
"Sheaffer",
"Waterman"
};
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}
}
try this one
http://www.mkyong.com/android/android-listview-example/
res/layout/list_fruit.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
ListView
public class ListFruitActivity extends ListActivity {
static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
"Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
"Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// no more this
// setContentView(R.layout.list_fruit);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,FRUITS));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources