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
Related
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
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
I don't understand DialogFragment at all. How to create one, how to get the user input out of it, and set it into a TextView.
I would like for the TITLE button, when clicked, to bring up a DialogFragment asking the user to enter the title of their Mood Board. The user enters a title. When they click the PostiveButton "Done", the user's title is set into the top left frame of the mood board, which has a TextView with a hint.
Please! Ask questions, because I don't really understand the dialog setup.
Here is a picture of my main_layout, in my MainActivity. Every element has an "#+id/".
The solution you are looking for is a callback:
Create an interface with a method to use as a callback
Implements the interface on the activity
Create the dialog fragment and in onAttach get the interface
Show the dialog fragment on the activity
On dismiss the dialog fragment pass the text using the instance of the interface
interface Callback {
updateText(String text)
}
class CoolActivity... implements Callback
onCreate {
//find your views
showDialogBtn.setOnClickListener(...
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("yourTag");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = ExampleDialogFragment.newInstance();
dialogFragment.show(ft, "yourTag");
)
}
#Override
updateText(String text) {
youtView.setText(text)
}
class CoolDialogFragment extend DialogFragment {
private Callback callback;
#Override
void onAttach(Context context) {
callback = (Callback) context
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_fragment_example, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//find the views in the dialog fragment
closeBtn.clickListener(...
callback.updateText(edittext.getText().toString())
dismiss()
)
}
}
Here is a gist of a dialog fragment
https://gist.github.com/cutiko/7e307efcf7492ea52ef05cd90f9e3203
The problem is you want to connect a dialog fragment with a another component, and you want to do it straigth forward. This is not considered a good practice because yiu create 2 componentes higly attached, so the best would be to use data persistence and some form of react programming
You can make your mood board title textview static then call it to the alertdialog with edittext to set it text (setText)
like this.
final EditText edittext = new EditText(MainActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Input Title")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
YourCustomDialog.your_title_textviewMoodboard.setText(edittext.getText().toString());
}
})
.setNegativeButton("Back", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
in your custom dialog. declare your textview static globally
public static TextView your_title_textviewMoodboard;
I am trying to use Bundle to send data from an activity to a fragment. The activity is receiving the input from a dialogbox when the user clicks on the actionbar add icon. The button also opens the dialogbox but it sends the data straight to the fragment (I'm trying to learn the difference between activity and fragment and to interact with the dialogfragment). None of the solutions on the internet have worked for me, and I was hoping someone can help
I have provided a visualization to aid in my explanation of the issue. So initially, I click the action add icon that opens the dialogbox (2nd pic), when I enter an input, it doesn't alter the data on the fragment. Only when I press the action add icon for a second time, does the first input get updated (3rd pic). Also you may notice that it says "Bundle{[Dialog Input = First Input]}" where First Input is the user input. How do I change this to just, First Input. I tried clearing the textview before setting the value, but that doesn't work. Now lastly when I press the button, it opens the dialogbox and when I enter in data, the data from the action add icon (handled in activity then data sent to fragment) overlaps with the data from the button (data sent straight to fragment). Any help would be appreciated. Thanks in advance.
MainActivity:
public class MainActivity extends AppCompatActivity implements
MyCustomDialog.OnInputSelected{
public String dialogInput;
FragmentManager fragmentManager;
#Override
public void sendInput(String input) {
dialogInput = input;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu, this adds items to the action bar if it is present
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle action bar clicks here. The action bar will automatically handle clicks on the home/up button
//so long as you specify a parent activity in AndroidManifest.xml
switch(item.getItemId()){
case R.id.action_add:
MyCustomDialog dialog = new MyCustomDialog();
dialog.show(getSupportFragmentManager(), "MyCustomDialog");
//Trying Bundle to pass data, dialog input between activity and fragment
Bundle bundle = new Bundle();
bundle.putString("Dialog Input", dialogInput);
//Set Fragment class arguments
MainFragment fragment = new MainFragment();
fragment.setArguments(bundle); //set argument bundle to fragment
fragmentManager.beginTransaction().replace(R.id.MainFragment,fragment).commit(); //now replace Mainfragment
Toast.makeText(this, "Action_Add Clicked Successfully", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
MainFragment:
public class MainFragment extends Fragment implements MyCustomDialog.OnInputSelected{
TextView InputDisplay;
Button OpenDialog;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
InputDisplay = view.findViewById(R.id.InputDisplay);
OpenDialog = view.findViewById(R.id.Open_Dialog);
//Getting Main Activity dialog information with Bundle, that was received from toolbar add
Bundle bundle = getArguments();
if(bundle != null){
String dialogInput = bundle.toString();
//Clearing since Fragment call and activity call overlap each other.
InputDisplay.setText("");
InputDisplay.clearComposingText();
InputDisplay.setText(dialogInput);
}
//String dialogInput = this.getArguments().getString("Dialog Input");
OpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("MainFragment", "onClick: opening dialog");
MyCustomDialog customDialog = new MyCustomDialog();
customDialog.setTargetFragment(MainFragment.this, 1);
customDialog.show(getFragmentManager(), "MyCustomDialog");
}
});
return view;
}
#Override
public void sendInput(String input) {
InputDisplay.setText("");
InputDisplay.setText(input);
}
}
My Custom Dialog:
public class MyCustomDialog extends DialogFragment {
private EditText Input;
private TextView ActionOK, ActionCANCEL;
private OnInputSelected onInputSelected;
public interface OnInputSelected{
void sendInput(String input);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
Fragment onInputSelected_fragment = getTargetFragment();
Activity onInputSelected_activity = getActivity();
if(onInputSelected_fragment != null){
onInputSelected = (OnInputSelected) onInputSelected_fragment;
}else{
onInputSelected = (OnInputSelected) onInputSelected_activity;
}
//throw new RuntimeException("Custom Dialog onAttach Listener was NULL");
}catch(ClassCastException e){
Log.e("Custom Dialog", "onAttach: ClassCastException: " + e.getMessage());
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_my_custom, container, false);
Input = view.findViewById(R.id.Input);
ActionOK = view.findViewById(R.id.Action_OK);
ActionCANCEL = view.findViewById(R.id.Action_CANCEL);
ActionCANCEL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getDialog().dismiss();
}
});
ActionOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onInputSelected.sendInput(Input.getText().toString());
getDialog().dismiss();
}
});
return view;
}
}
How do I change this to just, First Input.
your output is printed like this "Bundle{[Dialog Input = First Input]}" because you are directly doing bundle.toString(); instead of getting the value you have stored in the bundle.
change the above to this
String dialogInput = bundle.getString("Dialog Input")
InputDisplay.setText(dialogInput);
the data from the action add icon overlaps with the data from the button
Clear the existing text in the text view before setting the new value like this
String dialogInput = bundle.getString("Dialog Input")
InputDisplay.setText(");
InputDisplay.setText(dialogInput);
Also, I noticed that all the variable names that you have used are not following camel case I suggest you correct that as well.
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)