So I have this dialog box that pops up.
The buttons, however, are unresponsive. The debug lines inside of the onClick methods aren't being reached.
What am I doing wrong or not doing?
Here's my code, followed by my XML for the dialog box.
lv = new ListView(this);
lv.setAdapter(aa);
lv.setId(getTaskId());
setContentView(lv);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
TextView v=(TextView) view.findViewById(R.id.info);
String str = (String) v.getText();
String ssid = str.substring((str.indexOf(" ")+1), str.indexOf(newline));
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setView(getLayoutInflater().inflate(R.layout.loginbox,(ViewGroup) view));
b.setPositiveButton(R.id.loginbutton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Log.i("Button","Log in");
}
});
b.setNegativeButton(R.id.cancelbutton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.i("Button","Cancel");
dialog.dismiss();
}
});
Log.i("Click",ssid);
}
});
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/background"
android:orientation="horizontal" >
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="16dp"
android:hint="#string/ssidlabel"
android:inputType="textEmailAddress"
android:text="#string/ssidlabel" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/username"
android:layout_marginTop="14dp"
android:ems="10"
android:fontFamily="sans-serif"
android:hint="#string/password"
android:inputType="textPassword"
android:text="#string/password" >
<requestFocus />
</EditText>
<Button
android:id="#+id/loginbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/username"
android:layout_below="#+id/password"
android:text="#string/login" />
<Button
android:id="#+id/cancelbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/loginbutton"
android:layout_alignBottom="#+id/loginbutton"
android:layout_alignRight="#+id/username"
android:text="#string/cancel" />
TextView v=(TextView) view.findViewById(R.id.info);
String str = (String) v.getText();
String ssid = str.substring((str.indexOf(" ")+1), str.indexOf(newline));
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setView(getLayoutInflater().inflate(R.layout.loginbox, null, false));
b.setPositiveButton(R.id.loginbutton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Log.i("Button","Log in");
}
});
b.setNegativeButton(R.id.cancelbutton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.i("Button","Cancel");
dialog.dismiss();
}
});
AlertDialog alertDialog = b.create();
alertDialog.show();
Log.i("Click",ssid);
You could try the following:
lv = new ListView(this);
lv.setAdapter(aa);
lv.setId(getTaskId());
setContentView(lv);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
TextView v=(TextView) view.findViewById(R.id.info);
String str = (String) v.getText();
String ssid = str.substring((str.indexOf(" ")+1), str.indexOf(newline));
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setView(getLayoutInflater().inflate(R.layout.loginbox,(ViewGroup) view));
b.setPositiveButton("Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Log.i("Button","Log in");
}
});
b.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.i("Button","Cancel");
dialog.dismiss();
}
});
b.show();
Log.i("Click",ssid);
}
});
And then you can delete your <Button>s from your xml. The .setPositiveButton and .setNegativeButton will create the buttons for you and there is no need to create them in the xml and reference them with R.id.
Related
I am making an app which has a main recycler view and an internal recycler view that goes inside the main recycler view. The problem is that the list of elements is not displayed inside the recycler view, I have tried several things that you mention in this forum but I have not had good results. I read about nestedscrollview but it has not worked either, the last thing I tried was what I leave you in the code. This works but it is not efficient since in the emulator there are times when paste the scroll view (so the data is displayed "in jerks"
recycler
public class adapterArguments extends RecyclerView.Adapter<adapterArguments.ViewHolder> {
private List<ListArguments> data;
private LayoutInflater inflater;
private Context context;
public String position_selected;
public static String argument;
public adapterArguments listArguments;
RecyclerView recyclerView_arguments;
public adapterArguments(List<ListArguments> itemList, Context context) {
this.data = itemList;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.compontents_arguments_recyclerview,null);
recyclerView_arguments= view.findViewById(R.id.recycler_argument);
return new adapterArguments.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ConexionSQliteHelper conn=new ConexionSQliteHelper(context,"db_testwuad_7",null,31);
holder.arguments.setText(data.get(position).getArguments());
holder.name_user.setText(data.get(position).getName_user());
holder.date.setText(data.get(position).getDate_arguments());
holder.position.setText(data.get(position).getPosition());
int id_argument_selected = data.get(position).getId();
position_selected = holder.position.getText().toString();
holder.list_contrarguments = conn.getContrarguments(id_argument_selected);
holder.recyclerView_contrarguments.setLayoutManager(new LinearLayoutManager(context));
holder.recyclerView_contrarguments.setHasFixedSize(true);
holder.listContrarguments = new adapterContrarguments(holder.list_contrarguments,context);
holder.recyclerView_contrarguments.setAdapter(holder.listContrarguments);
final int[] checkedItem = {-1};
if(position_selected.equals("A favor")){
holder.position.setBackgroundColor(Color.parseColor("#073FD7"));
}
else{
holder.position.setBackgroundColor(Color.parseColor("#FC0C1E"));
}
holder.addContrarguments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("Añadir un Contrargumento");
alertDialog.setMessage("¿Quieres añadir un contrargumento a este texto?");
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
argument = holder.arguments.getText().toString();
contrargument fragment = new contrargument();
Bundle args = new Bundle();
args.putString("argument", argument);
args.putInt("id",id_argument_selected);
fragment.setArguments(args);
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
holder.deleteDiscuss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("Eliminar argumento");
alertDialog.setMessage("¿Quieres eliminar un argumento a este texto?");
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
boolean user_create_debate = conn.verifyCreatorDebate(holder.name_user.getText().toString());
if(user_create_debate){
conn.deleteArgument(id_argument_selected);
data = conn.getArguments(id_argument_selected);
listArguments = new adapterArguments(data,context);
notifyDataSetChanged();
}
else{
Toast.makeText(context, "No puede eliminar el argumento,ya que no es el creador del texto", Toast.LENGTH_SHORT).show();
}
opinionUserOnPostDebate fragment = new opinionUserOnPostDebate();
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.detach(fragment).attach(fragment).commit();
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
holder.changePosition.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Cambio de postura");
final String[] listItems = new String[]{"Cambie de opinión","Me equivoque de botón","Otro"};
alertDialog.setSingleChoiceItems(listItems, checkedItem[0], new DialogInterface.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(DialogInterface dialog, int which) {
checkedItem[0] = which;
}
});
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(position_selected.equals("A favor")){
//conn.changePosition(id_argument_selected,"En contra");
}
else{
//conn.changePosition(id_argument_selected,"A favor");
}
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
holder.Report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Reportar post");
final String[] listItems = new String[]{"Opinión contiene lenguaje ofensivo","Opinión contiene información personal","Otro"};
alertDialog.setSingleChoiceItems(listItems, checkedItem[0], new DialogInterface.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(DialogInterface dialog, int which) {
checkedItem[0] = which;
}
});
alertDialog.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(position_selected.equals("A favor")){
//conn.changePosition(id_argument_selected,"En contra");
}
else{
//conn.changePosition(id_argument_selected,"A favor");
}
}
});
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView arguments,name_user,date,position;
ImageButton addContrarguments,deleteDiscuss,addFriend,changePosition,Report;
List<ListContrarguments> list_contrarguments;
RecyclerView recyclerView_contrarguments;
public adapterContrarguments listContrarguments;
public ViewHolder(#NonNull View itemView) {
super(itemView);
arguments = itemView.findViewById(R.id.arguments_posted);
name_user = itemView.findViewById(R.id.name_arguments);
date = itemView.findViewById(R.id.date_arguments);
position = itemView.findViewById(R.id.position);
addContrarguments = itemView.findViewById(R.id.comments);
deleteDiscuss = itemView.findViewById(R.id.delete);
changePosition = itemView.findViewById(R.id.change_position);
addFriend = itemView.findViewById(R.id.add_friend);
Report = itemView.findViewById(R.id.report_argument);
recyclerView_contrarguments = itemView.findViewById(R.id.recycler_contrargument);
recyclerView_contrarguments.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView rv, #NonNull MotionEvent e) {
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_MOVE:
rv.getParent().requestDisallowInterceptTouchEvent(true);
break;
}
return false;
}
#Override
public void onTouchEvent(#NonNull RecyclerView rv, #NonNull MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
}
}
layout.compontents_arguments_recyclerview.xml:external recyclerview
<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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<TextView
android:id="#+id/position"
android:textColor="#color/white"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textStyle="bold"
android:textSize="25dp"
android:background="#0AA842">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/image_person_contrarguments"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="15dp"
android:layout_marginRight="5dp">
</ImageView>
<TextView
android:id="#+id/name_arguments"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="15dp"
android:textSize="14sp"
>
</TextView>
<TextView
android:id="#+id/date_arguments"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
>
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/arguments_posted"
android:layout_width="match_parent"
android:layout_height="140dp"
>
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal"
android:background="#FEFEFE"
>
<ImageButton
android:id="#+id/comments"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/add_comments"
android:background="#FEFEFE"
android:layout_marginLeft="50dp"
>
</ImageButton>
<ImageButton
android:id="#+id/delete"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/delete"
android:background="#FEFEFE"
>
</ImageButton>
<ImageButton
android:id="#+id/change_position"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/change_opinion"
android:background="#FEFEFE"
>
</ImageButton>
<ImageButton
android:id="#+id/add_friend"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/add_friend"
android:background="#FEFEFE"
>
</ImageButton>
<ImageButton
android:id="#+id/report_argument"
android:layout_width="60dp"
android:layout_height="match_parent"
android:src="#drawable/display_report"
android:background="#FEFEFE"
>
</ImageButton>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#A4A1A1"
>
</View>
<include
layout="#layout/recyclerview_contrarguments"
android:layout_width="match_parent"
android:layout_height="281dp">
</include>
</LinearLayout>
</LinearLayout>
</LinearLayout>
recyclerviee_contrarguments:intern recyclerview
<?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">
<androidx.core.widget.NestedScrollView
android:id="#+id/scroll_discuss"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_contrargument"
android:layout_width="442dp"
android:layout_height="match_parent"></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Check to see if this helps.
https://stackoverflow.com/a/37338715/19652887
Also, can u try changing the parent layout of your recycler view from linear layout to constraint layout and use recycler view's width as 0dp?
That's what fixed my problem
Hope this helps.
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/device_toolbar">
<com.google.android.material.card.MaterialCardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_3sdp"
android:layout_marginBottom="#dimen/_50sdp"
android:elevation="#dimen/_5sdp"
app:cardCornerRadius="#dimen/_20sdp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/_10sdp"
android:paddingVertical="#dimen/_10sdp"
android:paddingStart="#dimen/_5sdp"
android:paddingEnd="#dimen/_5sdp">
.......(other views).......
<com.google.android.material.button.MaterialButton
android:id="#+id/grant_storage_permission"
style="#style/Widget.Material3.Button.OutlinedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_10sdp"
android:text="Grant Permission"
android:textColor="#color/color_on_primary_light"
android:textSize="#dimen/_11ssp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/storage_text"
app:strokeColor="#color/color_secondary_variant_light" />
<androidx.constraintlayout.widget.Group
android:id="#+id/group_storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
app:constraint_referenced_ids="grant_storage_permission, storage_text" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/storage_rec_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/used_ram_text"
android:layout_marginTop="#dimen/_10sdp" />
<LinearLayout
android:id="#+id/storage_group_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/_20sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/grant_storage_permission" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.google.android.material.card.MaterialCardView>
</androidx.core.widget.NestedScrollView>
In my application I have button to which displays an AlertDialog. The AlertDialog has a CheckBox. Now I have to call a function if the checkbox is checked, and a different function if its not checked.
AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AlertDialogTheme);
builder.setTitle("Delete Completed Tasks:");
View view = getLayoutInflater().inflate(R.layout.del_completed,null);
builder.setView(view);
builder.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
CheckBox cb = findViewById(R.id.checkbox);
if(cb.isChecked()){
helper.delCompAndRec();
}
else helper.delCompleted();
}
});
builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
The problem is I always get the cb.isChecked() value as False, even if its checked. How do I solve this?
AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AlertDialogTheme);
builder.setTitle("Delete Completed Tasks:");
View view = getLayoutInflater().inflate(R.layout.del_completed,null);
final CheckBox cb = view.findViewById(R.id.checkbox); //or declare as global variable
builder.setView(view);
builder.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(cb.isChecked()){
helper.delCompAndRec();
}
else helper.delCompleted();
}
});
builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
You need to define checkbox in your design xml. And then you can access that checkbox via view.findViewById(R.id.checkbox).
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat);
builder.setTitle("Delete completed task");
View view = getLayoutInflater().inflate(R.layout.del_completed, null);
final CheckBox cb = view.findViewById(R.id.checkbox); //like defined here
builder.setView(view);
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(cb.isChecked()){
helper.delCompAndRec();
}
else {
helper.delCompleted();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
In xml declare like this
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="30dp"/>
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"
android:textSize="25sp"
android:text="Check this for test"/>
</androidx.constraintlayout.widget.ConstraintLayout>
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 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);
}
}