How to call dialog from fragment - java

When I click on cardview dialog has to be opened. So this is my onClick method in fragment class.
public class Entry_Fragment extends Fragment implements
View.OnFocusChangeListener, View.OnClickListener {
public void onClick(View view) {
if(view == cdAddWork)
{
if(actvEntryCategory.getText().toString().trim().equals("Installation")){
try {
InstActivityDialog dlg;
dlg = new InstActivityDialog(getFragmentManager(),getActivity().getApplicationContext());
dlg.show();//here I am passing this fragment and context as parameters to the constructor in that dialog.
}catch (Exception e){
}
}
}
}
}
This is my dialog class
public class InstActivityDialog extends Dialog {
public InstActivityDialog(FragmentManager fm, Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installation_dialog); //layout for dialog
setTitle("Installation Activity");
}
}
when I click on cardview in fragment, I need to open the dialog. For that In onClick method I call the dialog. I wanted to pass current fragment and context to the dialog.
What mistake I did while passing fragment and context as parameters to the constructor? And also while receiving argument in the constructor?
How to pass fragment and context as parameters?
Any help would be appreciated.

If your dialog is not showing then problem is in line blow.
InstActivityDialog dlg = new InstActivityDialog(getSupportFragmentManager(),getApplicationContext());
Dialog is bind to Activity's Context not Aplication Context. So use it like below.
InstActivityDialog dlg = new InstActivityDialog(getSupportFragmentManager(),getActivity());
dlg.show();
And for better implementation of Dialog with FragmentManager i suggest to use DialogFragment.

Related

Pass string value from FragmentContainerView to the Activity on button clicks

I've created an FragmentContainerView called GamePadFragment in MainActivity and I would like to get data from the fragment to the main activity. As the FragmentContainerView is relatively new method. I cannot find much info onto it.
I've placed multiple buttons on the FragmentContainerView. May I know how to get data pass (string) from the fragment on a button in FragmentContainerView is clicked.
String Pass:
from the `GamePadFragment` (FragmentContainerView) --> the Activity holding it
on button clicks
The current code in Main Activity is like:
FragmentContainerView gamePadFragment;
public MainActivity() {
super(R.layout.activity_main);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gamePadFragment = findViewById (R.id.gamePadFragment);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.gamePadFragment, GamePadFragment.class, null)
.commit();
}
// Set Default Appearance
//int wd = gamePadFragment.getWidth();
//gamePadFragment.setLayoutParams(new RelativeLayout.LayoutParams(wd, wd));
}
Use callback
interface MyCallback{
void click(String data);
}
Activity implements this interface
class MyActivity implements MyCallback
send delegate to your fragment,
call callback function in your fragment

How do I connect a button to a Dialog that will edit a TextView, within a FrameLayout, with a users input?

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;

How can i create an Alert Dialog Builder in a RecyclerView.Adapter class

HoAlertDialogBuilder in my RecylerView.Adapater class i get an error saying "in Builder cannot to the com.example.john.atsnotify.Adapter.PupilGroupAdapter class"
i can easily create an alert dialog Builder in a regular activity class which extends AppCompatActivity but not in an Adapter class. why?
https://pastebin.com/WqXCG1ChAlertDialog.Builder builder = new AlertDialog.Builder(PupilGroupAdapter.this);
The argument to the constructor (for which you are currently passing PupilGroupAdapter.this) must be of type Context. Your adapter is not a Context, so this is failing.
You can retrieve a context from any View instance via the getContext() method. In your case, you're trying to show the alert dialog from a button click, so you can use the context of the view passed to the click listener:
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
// ...
viewHolder.btnAdd.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
showAlertDialog(view.getContext()); // pass the context here
}
} );
}
private void showAlertDialog(Context context) { // receive the context here
AlertDialog.Builder builder = new AlertDialog.Builder(context); // use the context here
}
Was looking for a similar way and Context did not help. Found a solution through chat history of https://chat.stackoverflow.com/rooms/110530/discussion-between-sukhbir-and-amir-p
Implemented it in my code with Adapter constructor parameter like so:
public AdapterClass(..., Activity abc, ...){
this.abc = abc;
}
In my activity class initiating the recycler adapter:
AdapterClass newAdapter = new AdapterClass(..., CurrentActivity.this, ...);
And alert dialog in RecyclerAdapter onBindViewHolder class:
public void startAlert(..., Activity passedActivity, ...){
AlertDialog.Builder aB = new AlertDialog.Builder(passedActivity);
...
}

Closing a view class and opening another view class

I call a view class from my activity. Then the view class calls the same activity. Here is the problem, once the activity comes back up, it won't register any more button pushes.(I'm trying to call another view class. Here is some code:
View Class
public class AnimationView extends View {
Activity myActivity;
//...
public AnimationView(Context context, Activity activity) {
super(context);
//...
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//...
myActivity.setContentView(R.layout.activity_home);
}
}
Home Activity
public class HomeActivity extends AppCompatActivity {
private AnimationView mDrawViewA;
///...
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawViewA = new AnimationView(this,this);
start = (Button) findViewById(R.id.startButton);
//...
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//...
setContentView(mDrawViewA);
//calls more views
//......
});
}
I realize now maybe I should have been calling the view classes in different activities, but I would very much like a get all the view classes working within the same activity.
The problem is you're calling setContentView every time you press the "start" button. This method will overwrite the current layout (if any) with the new value you're setting.
What you can do to get the result you're expecting, which, from what I understand, is to add a new AnimationView to your current layout on every button click, you can try something like this:
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AnimationView animationView = new AnimationView(getApplicationContext());
// I'm using ConstraintLayout as an example, since I don't know exactly what layout you're using
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
// Set the layout params the way you want
addContentView(animationView, params); // This is where the magic happens
}
});
In short, addContentView is the method you should use when you want to add new views into your activity's root layout.
PS.: It's a terribly bad practice to let the views "know" the activity controlling it. It's always the opposite way around: the activity/fragment knows the view(s) it's controlling.

Create child Intent from Fragment

I'm using FragmentActivity for switching between Fragment. But I would like to have a Admin Button on a fragment, and when I click on it, a new fragment or activity appears like a child (with the back button in action bar).
How can I make it ?
Here is my code, that works, but the back button doesn't appear in action bar :
Fragment :
public class Reports extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (container == null) {
return null;
}
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
getActivity().startActivity(intent);
}
});
}
}
Activity (for the moment... but maybe Fragment if we need ?) :
public class LoginActivity extends ActionBarActivity {
public static final String TAG = LoginActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView emailText = (TextView) findViewById(R.id.emailText);
TextView passwordText = (TextView) findViewById(R.id.passwordText);
ParseUser.logInInBackground(emailText.getText().toString(), passwordText.getText().toString(), new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.i(TAG, "Yeahhh Login OK");
finish();
} else {
runOnUiThread();
}
}
});
}
});
}
Maybe I have to change something in Manifest ?
All you need to do is enable it inside the activity you're currently at.
When inside a FragmentActivity: getActionBar().setHomeAsUpEnabled(boolean).
Otherwise, inside a Fragment: getActivity().getActionBar().setHomeAsUpEnabled(boolean).
U need to override the onCreateOptionsMenu and onOptionsItemSelected. In the onCreateOptionsMenu method do the following : Inflate the menu into the action bar. You can define the contents of the menu item under res/menu folder.
Next in the onOptionsItemSelected method, you can handle the clicks of the back button added in the action bar. Also keep in mind one thing. In the manifest please use a theme which has action bar in it.
Example : Under the application tag use
android:theme="#android:style/Theme.Light" and not anything like android:theme="#android:style/Theme.Light.NoTitleBar
Well if you are starting a new Activity you can enable the back button in it by writing shouldDisplayHomeUp(); in the onCreate() method and on back should take you to the previous activity in the back stack.
And in the other case of adding a new Fragment you can take a look on this answer for reference as it mentions that when you add a new Fragment you add it to the back stack like this
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
this will make the back button take you to your previous Fragment

Categories