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);
}
}
Related
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);
I have created a Custom listview inside the AlertDialog and set data by parsing a list. I need to get the clicked value of the individual object of that clicked row. But listView.setOnItemClickListener is not working. I have tried to solve this problem, but couldn't find a way. Please help me to solve this.
Thanks..
here is my code
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select A Customer");
//insert array to constructor
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.product_list_pop_up, null);
final CustomerPopupAdapter testAdapter = new CustomerPopupAdapter(getContext(), customers_data);
ListView listView = dialogLayout.findViewById(R.id.product_list_view);
TextView cancel_btn = dialogLayout.findViewById(R.id.cancel_btn);
TextView done_btn = dialogLayout.findViewById(R.id.done_btn);
listView.setAdapter(testAdapter);
builder.setView(dialogLayout);
final AlertDialog alert = builder.create();
alert.show();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("selected Item", "ListView ");
// customerName = testAdapter.getItem(position);
// customer_name.setText((CharSequence) testAdapter.getItem(position));
alert.dismiss();
}
});
alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});
done_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});
here is my adapter
public class CustomerPopupAdapter extends ArrayAdapter<Customer> {
private List<Customer> list;
public CustomerPopupAdapter(Context context, List<Customer> test) {
super(context, R.layout.discount_popup_row, test);
this.list = test;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final Customer customer = list.get(position);
View customRow = inflater.inflate(R.layout.customer_popup_row, parent, false);
TextView customer_name = customRow.findViewById(R.id.customer_name);
TextView customer_id = customRow.findViewById(R.id.customer_id);
customer_id.setText(customer.getId());
customer_name.setText(customer.getName());
return customRow;
}
}
here is the custom_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/match_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/activity_margin_10dp"
android:weightSum="3">
<TextView
android:id="#+id/customer_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Username"
android:inputType="text"
android:layout_weight="1"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
<TextView
android:id="#+id/customer_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="id"
android:inputType="text"
android:layout_weight="2"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
</LinearLayout>
<View
android:id="#+id/bottom_border"
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_marginTop="#dimen/activity_margin_5dp"
android:background="#color/colorGrey" />
</LinearLayout>
Use your customers_data list to get the clicked value.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("selected Item", customers_data.get(position));
alert.dismiss();
}
});
You i am not sure why your code is not working if you can post the project that would be very really helpful or at least the whole activity ,so this is how you can easily display list in alert box .
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");
// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // horse
case 1: // cow
case 2: // camel
case 3: // sheep
case 4: // goat
}
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
Check the full reference https://stackoverflow.com/a/43532478/9638167
Don't use ListView, read this: Should we use RecyclerView to replace ListView? and other materials on google, RecyclerView is the way to go
I think what you need is:
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
//element selected is yourList.get(position);
}
});
Actually, this is an answer for this question. I have added android: inputType="text" to the code. It was the problem. I removed it and then it works perfectly.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/match_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/activity_margin_10dp"
android:weightSum="3">
<TextView
android:id="#+id/customer_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Username"
android:layout_weight="1"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
<TextView
android:id="#+id/customer_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="id"
android:layout_weight="2"
android:textColor="#color/colorBlack"
android:textSize="#dimen/text_size_18sp" />
</LinearLayout>
<View
android:id="#+id/bottom_border"
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_marginTop="#dimen/activity_margin_5dp"
android:background="#color/colorGrey" />
</LinearLayout>
The answer was given by the "I_A_Mok", All the credits should goes to him.
Please remove the android:inputType="text" from your xml. this will solve your problem. Thanks.
I'd need your help to do something in Android, in the following the use case.
I have created a custom dialog in Android, whose layout is:
dialog_threshold.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp">
<ImageView
android:src="#drawable/ic_media_route_on_03_dark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="center"
android:background="#FFFFBB33"
android:contentDescription="#string/set_target" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner_threshold" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layout_threshold">
<TextView
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/targetSelected"
android:layout_weight="1" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/threshold_operator_spinner"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/threshold_val"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
And in the Activity, when I click on a specific button, I have something like this, to create the custom dialog:
setThreshold_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(DiseaseActivity.this);
//Inflate the custom layout
View mView = getLayoutInflater().inflate(R.layout.dialog_threshold, null);
//Set title for dialog
mBuilder.setTitle("Set thresholds for your target");
//Define the spinner inside your custom layout
final Spinner mSpinner = (Spinner) mView.findViewById(R.id.spinner_threshold); //because it doesn't exist in the main layout, but only in the custom layout
//Define the ArrayAdapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DiseaseActivity.this,
android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.threshold_choices));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Choose a threshold option")) {
String ThresholdSelection = mSpinner.getSelectedItem().toString();
}
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if ((dialog2 != null) && dialog2.isShowing() && !mSpinner.getSelectedItem().toString().equalsIgnoreCase("Choose a threshold option")) {
dialog2.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
} else {
dialog2.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Set the positive and negative button for the custom dialog
mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
disease.setThreshold(mSpinner.getSelectedItem().toString());
if (!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Choose a threshold option")) {
Toast.makeText(DiseaseActivity.this,
mSpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT)
.show();
setInterval_button.setEnabled(true);
}
}
});
mBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
mBuilder.setView(mView);
dialog2 = mBuilder.create();
dialog2.show();
dialog2.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
});
What I want to do now is to add dynamically other components (like EditText or TextView) to the above Dialog before is it shown.
How can I do it?
Thanks in advance!
just create your custom view >> find the parent(in which viewgroup you want to add) >>> and add it. eg:-
mView.addView(new TextView(ActivityContext),LayoutParamss);
mBuilder.setView(mView);
I try to display some items in a Gridview and set button click listener. When the item was clicked, it shows a dialog box, if clicking yes, it will change the Imageview.
java coding
public class table extends AppCompatActivity implements AdapterView.OnItemClickListener{
GridView gridView;
my_adapter my_adapter;
String table_names[]={"1a","1b","1c","1d","2a","2b","2c","2d","3a","3b","3c","3d"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
gridView=(GridView)findViewById(R.id.gridview);
my_adapter=new my_adapter(this,table_names);
gridView.setAdapter(my_adapter);
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(final AdapterView<?> adapterView, final View view, final int i, long l) {
new AlertDialog.Builder(this)
.setTitle("Table number: "+adapterView.getItemAtPosition(i).toString())
.setMessage("Open Table?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
my_adapter.change_img(); // change to new image
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
my_adapter.change_img2(); // change back to original image
}
})
.show();
}
}
class my_adapter extends BaseAdapter{
ImageView imageView;
LayoutInflater inflater=null;
Context ctx;
String table_names[];
ArrayList store_table_no;
my_adapter(Context ctx, String table_names[]){
this.ctx=ctx;
this.table_names=table_names;
store_table_no=new ArrayList<Integer>();
for (int i=0;i<table_names.length;i++){
store_table_no.add(table_names[i]);
}
}
#Override
public int getCount() {
return store_table_no.size();
}
#Override
public Object getItem(int i) {
return store_table_no.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View row=view;
if(row==null){
inflater=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.single,null);
}
TextView tv_table_no=(TextView)row.findViewById(R.id.table_no);
imageView=(ImageView)row.findViewById(R.id.imageView);
tv_table_no.setText(""+store_table_no.get(i));
return row;
}
public void change_img(){
imageView.setImageResource(R.drawable.table_full);
}
public void change_img2(){
imageView.setImageResource(R.drawable.table3d2);
}
}
single.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="101"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/table_no"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="22sp" />
<ImageView
app:srcCompat="#drawable/table"
android:id="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="130dp"
android:layout_height="100dp" />
</RelativeLayout>
Here is a screenshot, please have a look
It simply doesn't change the imageview. Looks like something is wrong with my coding. anyone knows what's happening ?
You are implementing GridView's OnItemClickListener to show a dialog and getting decision from user for each item. When you are showing up a dialog it needs to update current clicked item of grid. But in your case you have change_img() in adapter. No position specification is given to the adapter.
To make it work, move your logic from activity to adapter. Handle the click events with the positions.
In your activity,
public class table extends AppCompatActivity{
GridView gridView;
my_adapter my_adapter;
String table_names[] = {"1a", "1b", "1c", "1d", "2a", "2b", "2c", "2d", "3a", "3b", "3c", "3d"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridView = (GridView) findViewById(R.id.grid);
my_adapter = new my_adapter(this, table_names);
gridView.setAdapter(my_adapter);
}
class my_adapter extends BaseAdapter {
LayoutInflater inflater = null;
Context ctx;
String table_names[];
ArrayList<String> store_table_no;
my_adapter(Context ctx, String table_names[]) {
this.ctx = ctx;
this.table_names = table_names;
store_table_no = new ArrayList<>();
store_table_no.addAll(Arrays.asList(table_names));
}
#Override
public int getCount() {
return store_table_no.size();
}
#Override
public Object getItem(int i) {
return store_table_no.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View row = view;
if (row == null) {
inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.single, null);
}
RelativeLayout layout = (RelativeLayout) row.findViewById(R.id.relative_layout);
TextView tv_table_no = (TextView) row.findViewById(R.id.table_no);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
tv_table_no.setText(store_table_no.get(i));
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(GridActivity.this)
.setTitle("Table number: " + store_table_no.get(i))
.setMessage("Open Table?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
imageView.setImageResource(R.mipmap.ic_launcher);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
imageView.setImageResource(R.drawable.icon);
}
})
.show();
}
});
return row;
}
}
}
In your xml file add id to Parent RElative Layout as follows,
single.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/relative_layout"
android:clickable="true"
android:layout_height="match_parent">
<TextView
android:text="101"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/table_no"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="22sp" />
<ImageView
app:srcCompat="#drawable/table"
android:id="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="130dp"
android:layout_height="100dp" />
</RelativeLayout>
I hope it will help you.
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