Android - How to check if EditText is empty and disable Button? [duplicate] - java

This question already has answers here:
How to disable Button if EditText is empty ?
(15 answers)
Closed 6 years ago.
I'm working on an Android app, most of it was with the help of tutorials and reading material, my app is somewhat basic, make some calculations and display the result to the user
What I have
I created a fragment guided by this tutorial and I just replaced the button and textview with my own EditText and Button
I have an EditText, a Button, and a TextView, these are the widgets the user see when the fragment is opened
My goal
I want the user to input values in the EditText and when s/he click the button the TextView displays the result of some calculations
What I did
I've been trying some other answers from here, here, here, here, but I don't know how to wire up the code, every time I write some pieces of code my app crashes and I don't know what else to do
Here is my code
public class Circle_Perimeter extends Fragment
{
EditText edtxt;
Button btn;
TextView txt;
public static Circle_Perimeter newInstance()
{
Circle_Perimeter fragment = new Circle_Perimeter();
return fragment;
}
public Circle_Perimeter()
{
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_circle__perimeter,container,false);
edtxt = (EditText)rootView.findViewById(R.id.editText);
btn = (Button)rootView.findViewById(R.id.button6);
txt = (TextView) rootView.findViewById(R.id.textView6);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
}
});
return rootView;
}
}
Question
How and where do I write the necessary code to make the EditText send a Toast warning the user the EditText is empty? or disable the Button if the EditText is empty?
EDIT: Really?? A downvote?? Instead of downvoting... Just give a warning or something else
EDIT 2: I already said that I did follow another answers from here and I couldn't make my code work that's why I'm here looking for an answer WITH my piece of code

To notify the text changes in EditText you need to use TextWatcher.
Please have a look at this document https://developer.android.com/reference/android/text/TextWatcher.html
public class Circle_Perimeter extends Fragment
{
EditText edtxt;
Button btn;
TextView txt;
public static Circle_Perimeter newInstance()
{
Circle_Perimeter fragment = new Circle_Perimeter();
return fragment;
}
public Circle_Perimeter()
{
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_circle__perimeter,container,false);
edtxt = (EditText)rootView.findViewById(R.id.editText);
btn = (Button)rootView.findViewById(R.id.button6);
txt = (TextView) rootView.findViewById(R.id.textView6);
//Initially set it as disabled
btn.setEnabled(false);
//Add textWatcher to notify the user
edtxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//Before user enters the text
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//On user changes the text
if(s.toString().trim().length()==0) {
btn.setEnabled(false);
Toast.makeText(getActivity(), "Text can not be empty..",
Toast.LENGTH_SHORT).show();
} else {
btn.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable s) {
//After user is done entering the text
}
});
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//do your final job here
}
});
return rootView;
}
}

Its simple to check that edit text is empty
if{edittext.getText == null){}
or
if(editText.isEmpty){}
Also best way is make for button
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(edittext != null){
//do what u want for no empty button
}else{
//block ur button}
}
});

You can check the EditText for null instances using the TextUtils API that comes bundled with Android
if(!TextUtils.isEmpty(editText) {
//Do your desired work
}else {
//Notify user for rectification
}
To play around with the button, you can use either of them:
button.setVisibility(VIEW.GONE)
button.setEnabled(false)

Related

Change background using shared preference

I have an application that allows my users to customize the background of my application using buttons. My app works like this: First it will lead them to my main activity, where there is a button that they can press to customize the background. When they pressed that button, it will lead them to a dialog fragment that will give users an option to choose which background image they want. I'm able to change my background, however, the shared preference is not functioning correctly. When I close my app and open it, it changes back to my default background, but when I press the dialog fragment button, it then updates the background to whatever they chose.
So basically, the background only updates when I open the button that offers the background images.
I'm not sure if I explained it well so here is a gif of my
problem
The background only updates when I press the terrain button, does anyone have an idea to fix this? I'm still very new to android and java so I'm not sure if I'm just missing something...
PopupTheme.java
public class PopupTheme extends DialogFragment implements View.OnClickListener {
private ImageButton btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10;
private static final String BG_NAME = "bgName";
private static final String BG_KEY = "bg";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_popup_theme, container, false);
btn1 = view.findViewById(R.id.btn1);
btn2 = view.findViewById(R.id.btn2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
if (getBackground() != R.drawable.bgscreen1 ){
MainActivity.mainLayout.setBackgroundResource(getBackground());
}
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn1:
MainActivity.mainLayout.setBackgroundResource(R.drawable.bgscreen1);
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_SHORT).show();
storeBackground(R.drawable.bgscreen1);
break;
case R.id.btn2:
MainActivity.mainLayout.setBackgroundResource(R.drawable.bgscreen2);
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_SHORT).show();
storeBackground(R.drawable.bgscreen2);
break;
}
}
public void storeBackground(int background) {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(BG_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //accessing the shared pref
editor.putInt(BG_KEY, background);
editor.apply();
}
// getting the background
public int getBackground() {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(BG_NAME, Context.MODE_PRIVATE);
int selectedBG = sharedPreferences.getInt(BG_KEY, R.drawable.bgscreen1);
return selectedBG;
}
}
Main Activity.java
public class MainActivity extends AppCompatActivity {
private Button btnWatch, btnReadStory, btnFavorites, btnAbout, btnListen;
private ImageButton btnTheme;
static ConstraintLayout mainLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTheme = findViewById(R.id.btnTheme);
mainLayout = findViewById(R.id.layoutMain);
btnTheme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupTheme popupTheme = new PopupTheme();
popupTheme.show(getSupportFragmentManager(), "Popup Theme");
}
});
}
}
The problem is that you update background of your MainActivity only if you opened the PopupTheme dialog, So you need to move getBackground and update code from PopupTheme to the onCreate method on MainActivity so the code will executed when the user launch the app
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTheme = findViewById(R.id.btnTheme);
mainLayout = findViewById(R.id.layoutMain);
int background = getBackground();
if (background != R.drawable.bgscreen1 ){
mainLayout.setBackgroundResource(background);
}
// Other code on onCreate
}
// Move getBackground method here from PopupTheme
Note: you can use -1 as default value of background and check if it's -1 that mean the user use the default background

set Title for popup in android

I want to build application in which I've search button when I clicked on this I get popup where I can search for student name.
I created all of this but I want to set Title for this dialog like "search for student by name"
this is my code
public class pop_up extends DialogFragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.popup,container,false);
Button btn_search = view.findViewById(R.id.btn_search);
Button btn_close = view.findViewById(R.id.btn_close);
TextView result = view.findViewById(R.id.txt_found);
EditText text = view.findViewById(R.id.txt);
btn_search.setOnClickListener(this);
btn_close.setOnClickListener(this);
getDialog().setTitle("Search for Student by Name");
return view;
}
#Override
public void onClick(View view) {...}
}
and this is code in MainActivity
final FragmentTransaction fragment = getFragmentManager().beginTransaction();
final pop_up pop = new pop_up();
Button btn = findViewById(R.id.btn_student);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pop.show(fragment,null);
}
});
Dialog appears but without title, so How can I set Title for it ?
you are crating dialog on completely wrong way
at first you should use onCreateDiolog insted of onCreatView
you should call AlertDialog.Builder to make dialog
read this doc to know how to use dialogs:https://developer.android.com/guide/topics/ui/dialogs#java
i have project that have bunch of dialog i leave a link if you want more example:
https://github.com/ErfanDP/Erfan_Delavari_HW13_Maktab36

How can I get the text from EditText of a recyclerview item when user clicks on a button of the same item?

I am designing a RecyclerView list. Each item of the Recyclerview contains a LinearLayout. This LinearLayout contains two views, the first one is an EditText and the second one is Button. When user taps on the button, it fires an onclick event. From onClick listener, I need to get the content of the EditText. I don't find a way to access the content of a sibling view when the user taps on another sibling view.
My question is not "how can I set on click listener to a button inside adapter". Most of the people answered how to set onClick listener to a button which is there inside the recyclerview item. My question is bit different, when I am inside onClick method which is fired from button, how will I access the edittext which is a sibling of button. Every item has one edittext, so when I click on a button how will I find the correct edittext?
For example, I have a recylerview of size 10. And each item of recyclerview contains a LinearLayout and inside linearlayout two item, one is an Edittext and the other one is a Button. when I tap on 7th items button, how will I get the text of 7th item's Edittext? I hope I have explained it well
Any help would be appreciated.
First of, you need two references: one to your EditText and one to your Button. You can get those in your ViewHolder. Next, you need an OnClickListener. The ViewHolder can conveniently also implement one but you could also use onBindViewHolder() for that.
Inside that OnClickListener you can filter out your id with a switch statement if you want to and then get the content of the EditText like this:
switch(viewId) {
case R.id.buttonId:
String text = editText.getText().toString();
// do something with that text
return true;
}
In case you implemented an OnClickListener in your ViewHolder you can then do this button.setOnClickListener(this); inside your ViewHolder to make sure onClick() is actually called when you click the button.
EDIT:
Here's some sample code that should work for your case. I'm implementing View.OnClickListener here as mentioned above.
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
EditText editText;
Button button;
public ViewHolder(View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.editText);
button = itemView.findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.button:
String text = editText.getText().toString();
break;
}
}
}
This is what it would look like if you were to do it in your onBindViewHolder() (in this case you would NOT implement the OnClickListener in your ViewHolder obviously):
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = holder.editText.getText().toString();
}
});
}
Step 1 :Make an abstract function in your adapter.
abstract void onButtonClicked(String text);
Step 2: Declare your adapter Abstract.
Step 3: Override the method (onButtonClicked(String text);) in your activity were you have instantiated the adapter.
Step 4: In your adapter inside the onClickListener for your button call the function :
onButtonClicked(editText.getText().toString());
and you'll get the string in your activity where you overrided the method.
You can use holder pattern for RecylcerView adapter. Then you can set click listener on your button and get the text from EditText.
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = simpleEditText.getText().toString()
}
});
}
}
You can do it inside your adapter which is being set on the recycler view.
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
}
}
And in the bindview holder you can access the views
public void onBindViewHolder(#NonNull final ImageAdapter.MyViewHolder holder, int position) {
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Your Code to access the edit text content
}
});
}
use a custom listener like this in the holder:
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView, final OnItemSelectedListener listener) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String text = simpleEditText.getText().toString();
if(listener != null) listener.onItemSelected(text);
}
});
}
public interface OnItemSelectedListener{
void onItemSelected(String value);
}
}
Simply Use Your ViewHolder. It contains all the children you want. Implement the code inside your adapter where each item is inflated. Here is an example.
//inside the onBindViewHolder
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = viewHolder.editText.getText().toString();
Log.d("output", text);
}
});
If you are using FirebaseUI Implement this inside the populateViewHolder for older version and onBindViewHolder for the later versions.
People put -1 when they don't know the answer or when they do not understand question. So funny!! In onclick I took parent(getParent()) from the view and accessed the second child of the parent. With that I am able to access the content of the sibling.
` public void onClick(View v) {
for(int i = 0;i<parent.getChildCount();i++){
if(parent.getChildAt(i)instanceof EditText){
passwordView = (EditText)parent.getChildAt(i);
}
}
}`

How to make android edit text uneditable when switch is off?

I am brand new to android development and I am having difficulties trying to make my editText uneditable after a switch is set to off. The problem is that The switch function doesn't work. Even after it is set to off, I can still edit the text.
here is my code :
public void onCreate(Bundle savedInstanceState) {
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final View switch1 = (Switch) findViewById(R.id.editSwitch);
final EditText mEdit = (EditText) findViewById(R.id.bioTxt);
switch1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (switch1.getContext().toString().equals("On")) {
mEdit.setEnabled(true);
}
else if (switch1.getContext().toString().equals("Off")) {
EditText mEdit = (EditText) findViewById(R.id.bioTxt);
mEdit.setEnabled(false);
}
}
});
};
}
Switch has a function isChecked() which returns true if the Switch is in the 'On' position. Therefore your onClick method can just be:
public void onClick(View v) {
mEdit.setEnabled(switch1.isChecked());
}
switch1.getContext().toString()
What are you trying to do here? getContext on a view returns the activity that owns it. It does not return anything that will turn into "On" or "Off". You need to call some other function. I'm not sure which, as it looks like its a custom view.

Using android-color-picker in a fragment?

I am fairly new to android development and want to use the Android-Color_picker "AmbilWarna" inside a fragment. I am getting the error:
The constructor AmbilWarnaDialog(HomeFragment, int, new OnAmbilWarnaListener(){}) is undefined.
Is this because I am using a Fragment instead of a Fragment activity The tutorial I was using uses an Activity.
I am using the following tutorial:
http://wptrafficanalyzer.in/blog/android-color-picker-application-using-ambilwarna-color-picker-library/
public class HomeFragment extends SherlockFragment implements TabListener {
private View homeView;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
homeView = inflater.inflate(R.layout.homefragment, container, false);
Button sColorBtn = (Button) homeView.findViewById(R.id.button2);
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View v) {
colorpicker();
}
};
// Setting click event listener for the button
sColorBtn.setOnClickListener(clickListener);
return sColorBtn;
}
public void colorpicker() {
// initialColor is the initially-selected color to be shown in the rectangle on the left of the arrow.
// for example, 0xff000000 is black, 0xff0000ff is blue. Please be aware of the initial 0xff which is the alpha.
AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, 0xff0000ff, new OnAmbilWarnaListener() {
// Executes, when user click Cancel button
#Override
public void onCancel(AmbilWarnaDialog dialog){
}
// Executes, when user click OK button
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
Toast.makeText(getBaseContext(), "Selected Color : " + color, Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
Use this:
AmbilWarnaDialog dialog = new AmbilWarnaDialog(getActivity().getApplicationContext(), 0xff0000ff, new OnAmbilWarnaListener() {
// Executes, when user click Cancel button
#Override
public void onCancel(AmbilWarnaDialog dialog){
}
// Executes, when user click OK button
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
Toast.makeText(getBaseContext(), "Selected Color : " + color, Toast.LENGTH_LONG).show();
}
});
So you have to use getActivity().getApplicationContext() instead of this. It will return with the Context.
If you want a fragment solution for Color Picker, I have made a fork of android-color-picker where DialogFragment is used and is re-created on configuration change. Here's the link: https://github.com/lomza/android-color-picker

Categories