Custom Layout button is not working in an AlertDialog - java

I've been trying to fix this for a while now including searching online but I just can't find solution. Everyone saying you should add onClickListener and I did but it just does not work. When I click the button nothing happens. No verbose log ever appears. This is all in one class which implements Runnable so it can do stuff in the background and this EditText onClickListener is implemented inside onCreate of a class.
//Setting up EditText onClick Listeners
oof.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating custom layout dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final View inflatedView = getLayoutInflater().inflate(R.layout.dialog_box_popup, null);
builder.setView(R.layout.dialog_box_popup);
builder.setTitle("Edit");
final EditText indc = (EditText)inflatedView.findViewById(R.id.weightInDcEtxt);
Button incrementBtn = (Button)inflatedView.findViewById(R.id.incrementBtn);
Button decrementBtn = (Button)inflatedView.findViewById(R.id.decrementBtn);
//Enabling the increment button in a dialog
incrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("increment", "Button clicked: " + MiscVariables.rocket);
}
});
//Displaying dialog
AlertDialog dialog = builder.create();
dialog.show();
}
});
And here is the custom layout for the dialog using ConstraintLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<Button
android:id="#+id/decrementBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:text="-"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/incrementBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="+"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/weightInDcEtxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:ems="10"
android:gravity="center"
android:inputType="numberDecimal"
android:text="#string/editTextFromDialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/incrementBtn"
app:layout_constraintStart_toEndOf="#+id/decrementBtn"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayou
From there I have no idea what to do. If anyone can help me out I would appreciate it thanks!

I've found a solution. Here is the code:
//Setting up EditText onClick Listeners
oof.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating custom layout dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(R.layout.dialog_box_popup);
builder.setTitle("Edit");
//Enabling the increment button in a dialog
incrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("increment", "Button clicked: " + MiscVariables.rocket);
}
});
//Displaying dialog
AlertDialog dialog = builder.create();
dialog.show();
final EditText indc =
(EditText)inflatedView.findViewById(R.id.weightInDcEtxt);
Button incrementBtn =
(Button)dialog.findViewById(R.id.incrementBtn);
Button decrementBtn =
(Button)dialog.findViewById(R.id.decrementBtn);
}
});
Inflated view was useless here. All had to be accessed by doing dialog.findViewById.

final View inflatedView = View.inflate(getActivity(), R.layout.dialog_box_popup, null);
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setView(inflatedView);
final EditText indc = (EditText) inflatedView.findViewById(R.id.weightInDcEtxt);
Button incrementBtn = (Button) inflatedView.findViewById(R.id.incrementBtn);
Button decrementBtn = (Button) inflatedView.findViewById(R.id.decrementBtn);
//Enabling the increment button in a dialog
incrementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Hellloo", Toast.LENGTH_SHORT).show();
}
});
alert.show();
Try this, Hope this solution will be work...!!!

Related

Save state from checkbox in custom Dialog

Guys I have create an Custom dialog with one edit text and one checkbox with this XML code
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/dialog_rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#000000"
>
<TextView
android:id="#+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:padding="5dp"
android:text="Velocidade de Trabalho"
android:textColor="#ffffff"
android:textSize="32dp" />
<EditText
android:id="#+id/et_name"
android:layout_width="946dp"
android:layout_height="105dp"
android:layout_below="#id/dialog_title"
android:fontFamily="#font/digital"
android:hint="Digite a Taxa Desejada"
android:inputType="number"
android:maxLength="3"
android:textColor="#ffffff"
android:textSize="50dp"
tools:ignore="HardcodedText" />
<CheckBox
android:id="#+id/checkbox"
style="?android:attr/textAppearanceMedium"
android:layout_width="1000dp"
android:layout_height="71dp"
android:text="Habilitar GPS"
android:textColor="#ffffff"
android:textSize="32dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="172dp" />
<Button
android:id="#+id/dialog_negative_btn"
android:layout_width="220dp"
android:layout_height="110dp"
android:layout_below="#+id/et_name"
android:layout_centerVertical="true"
android:layout_marginTop="92dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:layout_toStartOf="#+id/dialog_positive_btn"
android:layout_toLeftOf="#id/dialog_positive_btn"
android:background="#ffffff"
android:text="CANCELAR"
android:textSize="22dp" />
<Button
android:id="#+id/dialog_positive_btn"
android:layout_width="220dp"
android:layout_height="110dp"
android:layout_below="#id/et_name"
android:layout_alignEnd="#+id/et_name"
android:layout_centerVertical="true"
android:layout_marginTop="90dp"
android:layout_marginEnd="1dp"
android:background="#ffffff"
android:text="CONFIRMAR"
android:textSize="22dp" />
in my fragment I created a method to show the dialog box, this dialog box is shown on click, after displaying the box I check the option in my checkbox and confirm using the positive button but when clicking again to show my dialogbox o checkbox state is not saved how can I save this state?
this is my method in fragment
private void showdialogGPS (){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_gps,null);
// Specify alert dialog is not cancelable/not ignorable
builder.setCancelable(false);
// Set the custom layout as alert dialog view
builder.setView(dialogView);
// Get the custom alert dialog view widgets reference
Button btn_positive = dialogView.findViewById(R.id.dialog_positive_btn);
Button btn_negative = dialogView.findViewById(R.id.dialog_negative_btn);
CheckBox btn_Habilita = dialogView.findViewById(R.id.checkbox);
final EditText et_name = dialogView.findViewById(R.id.et_name);
btn_Habilita.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked){
habilitagps = true;
}
else {
habilitagps = false;
}
}
});
// Create the alert dialog
final AlertDialog dialog = builder.create();
btn_positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Dismiss the alert dialog
dialog.cancel();
String name = et_name.getText().toString();
Toast.makeText(getActivity(),
"Velocidade de Trabalho : " + name + ("\u2705"), Toast.LENGTH_LONG).show();
// Say hello to the submitter
Txaplicacao.setText(name);
if (habilitagps){
Toast.makeText(getActivity(),
"GPS Habilitado " + ("\u2705"), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(),
"GPS Desabilitado " + ("\u2705"), Toast.LENGTH_LONG).show();
}
}
});
// Set negative/no button click listener
btn_negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Dismiss/cancel the alert dialog
//dialog.cancel();
dialog.dismiss();
Toast.makeText(getActivity(),
"Valor Não Alterado" + ("\u274c"), Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
just use SharedPreferences from Android Studio:

How to show Cancel and Accept button in AlertDialog Android

I am having troubles setting the two buttons on the lower part of the alert what I am trying to do is get a similar look to the IOS look of the buttons.
here is my current code:
public void openInstructions() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
setNewDateOnView();
dialog.cancel();
}
}).setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create();
TextView myMsg = new TextView(getActivity());
myMsg.setText("ExampleText ");
myMsg.setTextSize(15);
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
dialog.setView(myMsg);
dialog.setTitle("Confirm Date of Purchase");
dialog.setOnShowListener( new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface arg0) {
Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
negativeButton.setTextColor(0xFFFF0000);
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(0xFF0000FF);
}
});
dialog.show();
}
Example of how it looks right now:
How I wanted it to look:
To design Dialog like ios , we can create custom dialog using custom layout like this :
dialog_custom.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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="vertical"
app:layout_constraintHeight_max="wrap">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/custom_bg">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/title"
android:gravity="center"
android:text="Confirm Date of Purchase"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="17sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_ll"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/rebooking_single_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textAlignment="center"
android:text="#string/dummuy"
android:textColor="#android:color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/back_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<LinearLayout
android:id="#+id/rebooking_back_button_ll"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/ok_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".49"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Ok"
android:textAlignment="center"
android:textColor="#FF6363"
android:textSize="17sp"
android:textStyle="bold" />
<View
android:layout_width="0dp"
android:layout_weight=".01"
android:layout_height="match_parent"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<TextView
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAlignment="center"
android:paddingRight="10dp"
android:text="Cancle"
android:textColor="#7BC5FF"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Main_Activity
final Dialog dialog=new Dialog(FirstActivity.this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_custom);
TextView cancel_btn=dialog.findViewById(R.id.cancel_btn);
cancel_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
TextView ok_btn=dialog.findViewById(R.id.ok_btn);
ok_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
dialog.show();
Well, as a start, google recommends you use the Android Design Guidelines when creating Android apps, really you should be sticking to those as that's what your users will be used to (not Apple's).
Also there's no reason to be assigning the dialog a TextView if all you're doing is showing text, the AlertDialog provides this functionality with setMessage.
If that hasn't convinced you to stick to the normal design rules, the only other option would be creating a Custom View and assign it to the AlertDialog with setView(similar to how you're doing it with the TextView).
Here's a tutorial on creating a Custom View
You can create a custom view such as the one sent and inflate it
Example:
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
View mView=getActivity().getLayoutInflater().inflate(R.layout.custom_layout, null);
mBuilder.setView(mView);
Button close = (Button) mView.findViewById(R.id.close);
Button OK = (Button) mView.findViewById(R.id.ok);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//close the dialog
hideDialog1();
}
});
OK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
Use .setNeutralButton that make place left most
TextView textview;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button =(Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher_background)
.setTitle("Alert Dialog Box Title")
.setMessage("Are you sure( Alert Dialog Message )")
.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Yes", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Cancel", Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("NO", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on NO", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
}
===============================================

OnItemClickListener is not firing

I am making an app that has a list of exercises to do displayed in a ListView. I am trying to let the user select an item from the list to start a new activity, but my OnItemClickListener is not firing. Here is my Activity, (not a listActivity, it is appCompatActivity):
ArrayList<Exercise> myExercises = new ArrayList<>();
AlertDialog.Builder alertDialogBuilder;
ArrayAdapter<Exercise> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
refreshList();
Button newExButton = (Button) findViewById(R.id.newExButton);
arrayAdapter = new ArrayAdapter<Exercise>(
this,
android.R.layout.simple_list_item_1,
myExercises );
ListView lv = (ListView) findViewById(R.id.actList);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("listener heard");
// selected item
int selection = position;
startExercise(selection);
}
});
lv.setAdapter(arrayAdapter);
}
public void refreshList(){
setContentView(R.layout.activity_list);
ListView lv = (ListView) findViewById(R.id.actList);
lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
lv.setAdapter(arrayAdapter);
}
public void startExercise(int selection){
Intent exIntent = new Intent(this, CommenceExercise.class);
Exercise chosenEx = myExercises.get(selection);
Bundle info = new Bundle();
info.putLong("duration", chosenEx.getTime());
info.putString("name", chosenEx.getName());
info.putString("description", chosenEx.getDescription());
exIntent.putExtras(info);
startActivity(exIntent);
}
The list is initially empty, but the user adds items by pressing a button. The button creates an alertDialog through the code below:
public void addNewActivity(View view) {
//get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.custom, null);
alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.exNameInput);
final EditText durInput = (EditText) promptsView
.findViewById(R.id.exDurInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
long duration = 0;
String exName;
exName = userInput.getText().toString();
duration = Integer.valueOf(durInput.getText().toString());
myExercises.add(new Exercise(exName, duration));
// create new exercise with user input
refreshList();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
And here is my xml:
<android.support.constraint.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"
android:descendantFocusability="blocksDescendants"
tools:context="com.example.mytimer.ListActivity">
<TextView
android:id="#+id/textView2"
android:layout_width="146dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="16dp"
android:text="Activities"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="16dp"
android:clickable="false"
android:layout_marginEnd="16dp" />
<Button
android:id="#+id/newExButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="87dp"
android:onClick="addNewActivity"
android:text="New Exercise"
android:textSize="18sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<ListView
android:id="#+id/actList"
android:layout_width="328dp"
android:layout_height="301dp"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/newExButton"
app:layout_constraintVertical_bias="1.0">
<requestFocus/>
</ListView>
<TextView
android:id="#+id/debugText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:clickable="false"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
</android.support.constraint.ConstraintLayout>
When I tap an item I've added to the list, nothing happens. I can tell that the OnItemClickListener is not being fired because the System.out line is never printed. I'm at a loss as to why I can't get it to work. Any help would be greatly appreciated. Thanks in advance.
You need to remove below listview attributes from xml:
android:descendantFocusability="blocksDescendants"
android:focusable="true"
android:clickable="true"
android:focusableInTouchMode="true"
Also, there is no need of refreshList() this is actually bad way of doing things, instead in your addNewActivity(), once your model is ready(probably on click of positive button) add that item to arrayAdapter and then do arrayAdapter.notifyDataSetChanged().
I hope this helps you!
I think problem in XML Please set ListView clickable true
please do some changes in XML
<ListView
android:id="#+id/actList"
android:layout_width="328dp"
android:layout_height="301dp"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:descendantFocusability="blocksDescendants"
android:focusable="true" // change this
android:clickable="true" // change this
android:focusableInTouchMode="true" // change this
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/newExButton"
app:layout_constraintVertical_bias="1.0">
<requestFocus/>
</ListView>
Change your refreshList method to below one
public void refreshList(){
arrayAdapter.notifyDataSetChanged();
}
What you're doing is, inflating a ListView again and setting new data to it rather than updating old one. And when you assign new value to ListView you forgot to set onClickListener.
It'll work.
That's really strange... your code should have worked... I would suggest you to try implementing the in your activity to include lv.setClcickable(true) and
lv.setEnable(true) :
public class MenuActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener{
ArrayList<Exercise> myExercises = new ArrayList<>();
AlertDialog.Builder alertDialogBuilder;
ArrayAdapter<Exercise> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
refreshList();
Button newExButton = (Button) findViewById(R.id.newExButton);
arrayAdapter = new ArrayAdapter<Exercise>(
this,
android.R.layout.simple_list_item_1,
myExercises );
ListView lv = (ListView) findViewById(R.id.actList);
lv.setClickable(true);
lv.setEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view , int
position, long id)
{
startExercise(position);
}
lv.setAdapter(arrayAdapter);
}
public void refreshList(){
setContentView(R.layout.activity_list);
ListView lv = (ListView) findViewById(R.id.actList);
lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
lv.setAdapter(arrayAdapter);
}
public void startExercise(int selection){
Intent exIntent = new Intent(this, CommenceExercise.class);
Exercise chosenEx = myExercises.get(selection);
Bundle info = new Bundle();
info.putLong("duration", chosenEx.getTime());
info.putString("name", chosenEx.getName());
info.putString("description", chosenEx.getDescription());
exIntent.putExtras(info);
startActivity(exIntent);
}
}
or add these three lines to your xml
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="true
android:descendantFocusability="blocksDescendants"
If there are any focusable child views then the first click will always be for focus
And I would Suggest You to use Custom ListView with Viewholder Pattern for efficiency or the Recyclerview of support Library this will make your scroll smooth and won't create extra View Objects... It will only create the View Object that's will fit the screen
Here is the Link for RecyclerView https://guides.codepath.com/android/using-the-recyclerview

Android - Click Button Inside alertDialog

I wonder how to click a Button inside of AlertDialog in Android and this is my code
activity_float_info.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button" />
MainActivity.java
QR_ = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_float_info, null);
MAIN_QR_SCAN = (LinearLayout) findViewById(R.id.MAIN_QR_SCAN);
MAIN_QR_SCAN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(MainActivity.this)
.setCancelable(Boolean.TRUE)
.setNegativeButton(getString(R.string.CANCEL), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.setView(R.layout.activity_float_info)
.show();
button = (Button)QR_.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setText("TEst");
}
});
}
});
I have inflate the layout..
I think the main problem is on
button = (Button)QR_.findViewById(R.id.button);
try this create a layout for dialog box
<TextView android:id="#+id/dialogtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#android:color/black"
android:text="Please enter the email address you used for the account"
/>
<EditText
android:id="#+id/emailedittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:ems="10"
android:padding="5dp"
android:cursorVisible="true"
android:singleLine="true"
android:background="#android:color/white"
android:textColor="#android:color/black"
android:hint="Enter Mail id"
android:textSize="20dp" >
<requestFocus />
</EditText>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal">
<Button
android:id="#+id/cancelbtn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="CANCEL"/>
<Button
android:id="#+id/okbtn"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Ok"/>
</LinearLayout>
Then create a dialog box using this layout and handle button clicks
final Dialog dialog = new Dialog(MainActivity.this);
// Include dialog.xml file
dialog.setContentView(R.layout.forgotpassword);
// Set dialog title
dialog.setTitle("ALERT!!");
// set values for custom dialog components - text, image and button
Button okbtn = (Button) dialog.findViewById(R.id.okbtn);
Button cancelbtn = (Button) dialog.findViewById(R.id.cancelbtn);
final EditText emailedittext = (EditText) dialog.findViewById(R.id.emailedittext);
dialog.show();
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// if decline button is clicked, close the custom dialog
cancelbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
okbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email=emailedittext.getText().toString();
//do something more here
}
});
Refer: https://coderzpassion.com/android-show-alertdialog/
Here is a hack to use AlertDialog:
public class CustomDialog extends AlertDialog {
protected CustomDialog(Context context) {
super(context);
}
}
And then in your Activity:
CustomDialog dialog = new CustomDialog(this);
View view = getLayoutInflater().inflate(R.layout.custom_dialog_layout,null);
dialog.setView(view);
Button button = (Button)view.findViewById(R.id.custom_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(YourActivity.this,"Your message", Toast.LENGTH_LONG).show();
}
});
dialog.show();
And the layout of the dialog (which has nothing in it barring the Button):
<?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">
<Button
android:id="#+id/custom_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="New Button" />
</RelativeLayout>
And you should be able to see a Toast when you click on the button. Hope this helps.
Dialog is like a popup window to show some options to users(options like accept/decline).
Using class android.app.Dialog to create dialog.
Using dialog.xml file to create custom dialog layout.
Example:
res/layout/dialog.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" >
<ImageView
android:id="#+id/imageDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
<TextView
android:id="#+id/textDialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:layout_toRightOf="#+id/imageDialog"/>
<Button
android:id="#+id/declineButton"
android:layout_width="100px"
android:layout_height="wrap_content"
android:text=" Submit "
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_below="#+id/textDialog"
android:layout_toRightOf="#+id/imageDialog"
/>
</RelativeLayout>
Java Code
// Create custom dialog object
final Dialog dialog = new Dialog(CustomDialog.this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog);
// Set dialog title
dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.textDialog);
text.setText("Custom dialog Android example.");
ImageView image = (ImageView) dialog.findViewById(R.id.imageDialog);
image.setImageResource(R.drawable.image0);
dialog.show();
Button declineButton = (Button) dialog.findViewById(R.id.declineButton);
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});

TextView isn't updating in Android

I'm making a simple "novelty" app that counts how many sneezes are done, it's more of a fun app that builds up experience until I do my huge project during the summer. I have two buttons, one adds a sneeze and the other clears how many sneezes there currently are. It holds the highest number of sneezes that there were previously. The problem is, the TextViews never update, they only initialize to zero. I used a Toast.makeText() to make sure that the buttons are working (they are). Any help is appreciated. Thanks
Java code:
public class MainActivity extends ActionBarActivity {
private int record_number = 0;
private int current_number = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
Toast.makeText(MainActivity.this, "Button Clicked " + current_number, Toast.LENGTH_SHORT).show();
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
TextView rec_text = (TextView) findViewById(R.id.record_num);
TextView cur_text = (TextView) findViewById(R.id.current_num);
if (current_number >= record_number)
{
record_number = current_number;
}
rec_text.setText(String.valueOf(record_number));
cur_text.setText(String.valueOf(current_number));
}
}
XML:
<RelativeLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.michail.sneezecounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sneeze Counter"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Record Number of Sneezes:"
android:id="#+id/textView"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one Sneeze"
android:id="#+id/addone"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="76dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Current Number of Sneezes"
android:id="#+id/clear"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/record_num"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Current Number of Sneezes:"
android:id="#+id/currentLabel"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/currentLabel"
android:layout_alignLeft="#+id/record_num"
android:layout_alignStart="#+id/record_num"
android:layout_marginTop="21dp"
android:id="#+id/current_num" />
</RelativeLayout>
You need to update the text of the TextViews inside the onClickListeners. In fact, all your logic for counting, clearing, and recording the record needs to be done in your onClickListeners (or methods called by them). Right now you only do it once in onCreate, then never again. You can do this in onCreate:
final TextView cur_text = (TextView) findViewById(R.id.current_num);
add_one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
current_number += 1;
cur_text.setText(Integer.toString(current_number);
}
});
And similar for the other TextView & onClickListener.
You only set the contents of your TextViews once. You should update them every time you get a click event. Specifically:
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
{
record_number = current_number;
rec_text.setText(String.valueOf(record_number));
}
cur_text.setText(String.valueOf(current_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
}
});
NOTE: if your variables current_number, record_number, cur_text, and rec_text aren't already declared as class member variables, you'll want to do that do that so that they're accessible once you leave the scope of the method you're doing all this in (I assume it's onCreate(...).
What you are going to need to do here is update the labels during the on click events of the button. You currently only update them on activity create. This doesn't execute every time there is a click. Can I answer any questions about the fixed up version below?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView rec_text = (TextView) findViewById(R.id.record_num);
final TextView cur_text = (TextView) findViewById(R.id.current_num);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
record_number = current_number;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}

Categories