I have an Activity that kicks off three fragments.
The first is a loading splash screen where I just want to show the name of the app for a couple seconds.
The second, in my current case, is a screen that gathers the users name and language.
The third fragment will gather which languages they would like to learn. I'm trying to use an Observable in my ViewModel to hold my data, but the info entered at the first fragment is being lost upon switching to the second fragment.
I think I'm running into two problems (or more) simultaneously:
I don't think I'm sharing my runOnceViewModel correctly across fragments
I don't think I'm using Observables quite right.
After permissions are checked from the splash screen, I fire a function (launchProfile) that loads the next fragment like this:
public void launchProfile(){
if(model.getLearnerPK() > 0){
learningScreenFragment fragment = new learningScreenFragment(model.getUser());
getParentFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment_container, fragment, null)
.commit();
} else {
runOnceNameAndNativeLangFragment fragment = new runOnceNameAndNativeLangFragment();
getParentFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment_container, fragment, null)
.commit();
}
}
Since this is a new user, the primary key will be 0 and so I load the runOnceNameAndNativeLangFragment:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Log.d(LOG_TAG, "RUNONCE: Gather Name and Native Language");
mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.runonce_name_native, container, false);
TransitionInflater TI = TransitionInflater.from(requireContext());
setEnterTransition(TI.inflateTransition(R.transition.slide_right));
return mBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
runOnceViewModelFactory factory = new runOnceViewModelFactory(requireActivity().getApplication());
model = new ViewModelProvider(this,factory).get(runOnceViewModel.class);
//super.onViewCreated(view,savedInstanceState); //remains of a road I tried to go down, but perhaps should have gone farther...
//model = new ViewModelProvider(requireActivity()).get(runOnceViewModel.class);
ArrayList<language> spinnerListLangs = model.getLangList();
nativeSLAdapter = new SpinLangAdapter(m_Context, android.R.layout.simple_spinner_dropdown_item, spinnerListLangs);
mBinding.spCreateNativeLang.setAdapter(nativeSLAdapter);
mBinding.spCreateNativeLang.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
language lang = nativeSLAdapter.getItem(position);
tmpNativeLangNo = lang.getLangNo();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
mBinding.btnNext.setOnClickListener(this::onClick);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnNext) {
String tmpName = mBinding.etCreateProfileName.getText().toString();
if(tmpNativeLangNo != null && !tmpName.equals("")){
model.getNewUser().observeOn(Schedulers.io()) //I'm doing something dumb here
.map(user -> {
user.setName(tmpName);
user.setNativeLang(tmpNativeLangNo);
return user;
});
runOnceSelectTargetLangsFragment fragment = new runOnceSelectTargetLangsFragment();
getParentFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment_container, fragment, null)
.commit();
} else {
Toast.makeText(m_Context,"Name and Native Language required.",Toast.LENGTH_SHORT).show();
}
}
}
If I put a breakpoint on "runOnceSelectTargetLangsFragment fragment = new runOnceSelectTargetLangsFragment();" then I can verify that model.getNewUser() returns an Observable with the name and native language of whatever I input on the UI. What's killing me is that once I load the next fragment (runOnceSelectTargetLangsFragment), and try to save the target languages in its click handler, the name and native language info are lost. Ala, I'm not sharing the viewmodel right (or, worse, I'm using an Observable when I shouldn't be -- side note: I chose to use an Observable because it makes handling the thread stuff quite a bit easier and I imagine I'll appreciate its flexibility down the road as the app becomes more complicated. At least, that's what I'm telling myself.)
Select Targets Fragment
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Log.d(LOG_TAG, "RUNONCE: Gather Target Languages");
mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.runonce_select_targets, container, false);
TransitionInflater TI = TransitionInflater.from(requireContext());
setEnterTransition(TI.inflateTransition(R.transition.slide_right));
return mBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
//runOnceViewModelFactory factory = new runOnceViewModelFactory(requireActivity().getApplication());
//model = new ViewModelProvider(this,factory).get(runOnceViewModel.class); //I think this was on the right track...maybe?
//super.onViewCreated(view,savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(runOnceViewModel.class);
mBinding.btnNext.setOnClickListener(this::onClick);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnNext) {
if(hasChecked()){
model.getNewUser().observeOn(Schedulers.io())
.subscribe(user -> {
user.setTargetLangs(getTargetLangs());
});
String restHereWearyTraveler = ""; //the inn :)
//...do more stuff
} else {
Toast.makeText(m_Context,"You must select at least one target language.",Toast.LENGTH_SHORT).show();
}
}
}
At the inn, model.getNewUser() returns an Observable with the target languages all set, but the name and native language info are gonezo.
View Model
public class runOnceViewModel extends AndroidViewModel {
private final profileRepository m_Repository;
private profileService PCS;
private ArrayList<language> m_Langs;
private Observable<User> newUser;
public runOnceViewModel(Application application, profileRepository newProfileRepo) {
super(application);
m_Repository = newProfileRepo;
m_Langs = m_Repository.getLanguages();
PCS = profileService.getInstance(m_Repository);
}
public Observable<User> getNewUser(){
if(newUser == null){
User tmpUser = new User();
newUser = Observable.just(tmpUser);
}
return newUser;
}
}
Related
1) In my application, the user may receive a lot of notifications from FCM
2) If the user has an application open, he needs to display the custom DialogFragment
3) If the DialogFragment is already displayed, then the next time the notification arrives, it is necessary to prohibit the repeated display of this DialogFragment
4) My dialogue code:
public final class NotificationEventDialog extends DialogFragment implements DialogInterface.OnKeyListener, View.OnClickListener {
private Activity mCurrentActivity;
private NotificationEventDialogListener mNotificationEventDialogListener;
public interface NotificationEventDialogListener {
void showEvent();
}
public NotificationEventDialog() {
}
public static NotificationEventDialog newInstance() {
NotificationEventDialog notificationEventDialog = new NotificationEventDialog();
notificationEventDialog.setCancelable(false);
return notificationEventDialog;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mCurrentActivity = (Activity)context;
try {
mNotificationEventDialogListener = (NotificationEventDialogListener) mCurrentActivity;
} catch (ClassCastException e) {
throw new ClassCastException(mCurrentActivity.toString() + " must implemented NotificationEventDialogListener");
}
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
LayoutInflater inflater = LayoutInflater.from(mCurrentActivity);
#SuppressLint("InflateParams") View view = inflater.inflate(R.layout.dialog_notification_event, null);
Button btnNotificationEventYes = view.findViewById(R.id.notification_event_dialog_yes);
btnNotificationEventYes.setOnClickListener(this);
Button btnNotificationEventNo = view.findViewById(R.id.notification_event_dialog_no);
btnNotificationEventNo.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(mCurrentActivity);
builder.setView(view);
return builder.create();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (getDialog() != null && getDialog().getWindow() != null) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().setOnKeyListener(this);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onDetach() {
super.onDetach();
mCurrentActivity = null;
mNotificationEventDialogListener = null;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notification_event_dialog_yes:
dismiss();
mNotificationEventDialogListener.showEvent();
break;
case R.id.notification_event_dialog_no:
dismiss();
break;
}
}
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
dismiss();
return true;
} else return false;
}
}
5) Each time I receive a notification from FCM, I create a dialog box:
DialogFragment notificationEventDialog = NotificationEventDialog.newInstance();
notificationEventDialog.show(getSupportFragmentManager(), "");
6) How to check if DialogFragment is already displayed? Every time I create a new object of this window and I cannot make it as Singleton, because This leads to a memory leak.
Found an answer in which a person suggests using Weak links to solve this problem:
Also you can store a weak link to the shown dialog in that singletone
class. Using such method, you can detect is your dialog currently
shown or not.
There was also such an answer:
I suggest to save link to the dialog in single instance class. In that
instance create method ensureShowDialog(Context context). That method
would check is current shown dialog or not. If yes, you can show the
dialog. In another casr you can pass new data you to the dialog.
But, honestly, I can’t quite understand how to use these tips in practice. Please can help with this realization or suggest another way? Thanks in advance.
You can use:
val ft: FragmentTransaction = fragmentManager!!.beginTransaction()
val prev: Fragment? = fragmentManager!!.findFragmentByTag("typeDialog")
if (prev == null) {
val fm = fragmentManager
val courseTypeListDialogFragment =
CourseTypeListDialogFragment()
courseTypeListDialogFragment.isCancelable = false
courseTypeListDialogFragment.setStyle(
DialogFragment.STYLE_NO_TITLE,
0
)
courseTypeListDialogFragment.setTargetFragment(this, 1)
if (fm != null) {
courseTypeListDialogFragment.show(ft, "typeDialog")
}
}
You can check if dialog fragment is showing by calling isAdded () inside DialogFragment or by
DialogFragment notificationEventDialog = NotificationEventDialog.newInstance();
notificationEventDialog.isAdded()
from activity
It will return true if fragment is added to an Activity, in case of dialog fragment - is shown.
You can store last shown dialog fragment date via putting System.currentTimeMillis() in SharedPreferences
I think you'v got the idea.
I have a tabhost with several tabs and each tab contain a certain number of operations which are listed in a listview. To populate that listview I use an ArrayList.
First time tabs are created evertything works fine. The issue comes when I try to filter the list by year. The process of filtering works fine as I can see the filtered list in debug and it's fine.
The issue is that after filtering, i recreate the tabs in order to fill all listviews again. To open tabs I use this code. It creates as many tabs as different currencies there are in the list:
public static void openFragments(FragmentTabHost tabHost, ArrayList<Posicion> positions, Class FragmentResumen, Class FragmentDetails ) {
//==========================================================================================
// This method open as many tabs as different currencies there are in positions list
//==========================================================================================
ArrayList<String> currencies = Currency.getDifferentCurrencies(positions);
tabHost.clearAllTabs();
for (int i = 0; i < currencies.size() + 1; i++) {
String tabName = "", tabSpec = "";
Class fragmentToOpen;
Bundle arg1 = new Bundle();
//A general tab is first created
if (i == 0)
{
tabName = "All";
tabSpec = "General";
arg1.putString("moneda", tabName);
arg1.putSerializable("posiciones", positions);
fragmentToOpen = FragmentResumen;
}
//The rest of tabs for currencies are created
else
{
tabName = currencies.get(i - 1);
tabSpec = "Tab" + (i - 1);
arg1.putString("moneda", tabName);
arg1.putSerializable("posiciones", positions);
fragmentToOpen = FragmentDetails;
}
tabHost.addTab(tabHost.newTabSpec(tabSpec).setIndicator(tabName), fragmentToOpen, arg1);
}
}
As I told before, this works fine always.
First time I need to create tabs I call it by using:
openFragments(tabHost, positions, FragmentResumenMedio.class, FragmentDetailsMedio.class);
Then I have a button that shows a DatePicker and when user selects a year I close the dialog and redraw tabs as follows:
ArrayList<Posicion> positionsFiltered = General.makeHardCopyOfArrayListPosition(positions);
for(Posicion posicion : positionsFiltered)
{
Boolean matchFilters = filterPositionsByYear(posicion, year + "");
if(matchFilters == false){
positions.remove(posicion);
}
}
General.openFragments(tabHost, positions, FragmentResumenMedio.class, FragmentDetailsMedio.class);
When I debug this last function I can see that positions have the correct value after filtering but when I click the new tab, it shows the list without filtering and I don't know how could I solve this issue.
Thanks a lot.
EDIT
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Initialize view and tabhost
View rootView = inflater.inflate(R.layout.fragment_medio, container, false);
tabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
tabHost.setup(getActivity(), getChildFragmentManager(), android.R.id.tabcontent);
return tabHost;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//onCreatedView is only called the first time so we must ensure that tabhost is not null before adding tabs
if(tabHost == null) {
tabHost = (FragmentTabHost) getView().findViewById(android.R.id.tabhost);
tabHost.setup(getActivity(), getChildFragmentManager(), android.R.id.tabcontent);
}
FloatingActionButton floatingActionButton = (FloatingActionButton) getView().findViewById(R.id.floatingButton);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
positions = new ArrayList<>(positionsFiltered);
createDialogWithoutDateField().show();
}
});
//Check if any update has been made since the last open
SharedPreferences prefs = getActivity().getPreferences(MODE_PRIVATE);
Boolean updateMedioRequired = prefs.getBoolean(updateOperationsMedioPlazo, true);
if (updateMedioRequired != null)
{
if (updateMedioRequired == true)
{
//Update variable that indicates if changes have been made or not
SharedPreferences.Editor editor = getActivity().getPreferences(MODE_PRIVATE).edit();
editor.putBoolean(updateOperationsMedioPlazo, false);
editor.apply();
//Check if there are previously stored operations
if (operations.size() > 0)
{
//Show a progressDialog as prices have to be downloaded from internet and this can be a time consumming task
progress = ProgressDialog.show(getActivity(), "Obteniendo precios",
"Un momento por favor...", true);
//Generate positions from operations list and wait for result in "onStockPriceResult". If there are no changes, positions variable has already values
if(positions.size() == 0) {
new Thread(new Runnable() {
#Override
public void run() {
positions = MedioPlazoCalculations.generatePositions(listener, getActivity(), operations);
}
}).start();
}
}
else
{
Toast.makeText(getActivity(), "Aún no se ha introducido ninguna operación", Toast.LENGTH_LONG).show();
}
}
else
{
//If no update needed, variable coming from MainActivity has positionList. Open as many new fragments as currencies there are in positionsList
General.openFragments(tabHost, positions, FragmentResumenMedio.class, FragmentDetailsMedio.class);
}
}
}
EDIT 2:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
{
if(getActivity()!=null)
{
Bundle bundle = this.getArguments();
positions = (ArrayList<Posicion>) bundle.getSerializable("posiciones");
moneda = (String) bundle.getString("moneda");
}
}
}
Edit 3: If I place the commented instruction, filtering does not work. If I remove it, filtering works but I cant filter again because the value of the list has the filtered version not the original one
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
positions = new ArrayList<>(positionsFiltered);
createDialogWithoutDateField().show();
}
});
I want to implement a setup assistant for my app which is shown when the user starts the app for the first time. I use a PageViewer for this which seems to work fine.
The first page asks the user for the default language. I want to refresh the page when the user selects its language from the RadioGroup. So I need a way to reload the fragment in the chosen language.
public class SetupAssistantLanguageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.setup_language_fragment, container, false);
((RadioGroup) view.findViewById(R.id.setup_language_radiogroup)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
String langcode = "";
if (i == R.id.setup_fragment1_languagechooser_en) {
langcode = "en";
} else {
langcode = "de";
}
((SetupAssistantActivity) getActivity()).changeLanguage(langcode);
SetupAssistantLanguageFragment.this.refreshView();
System.out.println("test1");
}
});
return view;
}
public void refreshView() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
System.out.println("test2");
}
}
Changing the language works but only for the pages that follow the first page. This is because the fragment needs to be reloaded when the language changed. I try to reload in refreshView().
The problem is: As soon as I press one radio button, I get an endless loop printing "test1" and "test2". Why is this method called again and again?
How can I reload the fragment exactly one time?
I got it:
In my fragment I first save the current language.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDisplayLang = getResources().getConfiguration().locale.getLanguage();
}
In onCreateView I only refresh the fragment when the language really changed.
((RadioGroup) view.findViewById(R.id.lecture_translator_setup_language_radiogroup)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
String chosenLangcode = i == R.id.setup_fragment1_languagechooser_en ? "en" : "de";
if (!chosenLangcode.equals(currentDisplayLang)) {
currentDisplayLang = chosenLangcode.toString();
((SetupAssistantActivity) getActivity()).changeLanguage(chosenLangcode);
SetupAssistantLanguageFragment.this.refreshView();
}
}
});
Is this the recommended way?
I am learning Android and came across very strange behavior. I am using Retrofit2 as REST library in android (using asynchronous calls). I want to send authCode and TokenId as Google advise it on my server. When I check if user has set password I do a response. If I return code 206 means that user has not yet set password on my back-end server.
So I want to start a fragment that user will enter password (I am also say that I defined LoginFragment and RegistrationFragment that both work on this Activity). But here is the trick, Fragment get called and when my onCreateView is executed there but TextView and Button has null value why is that? I assume that there is a problem since this is run on background thread but I may be mistaken. Is there a better way to achieve what I want?
My Retrofit call:
private void sendTokenToServer(String idToken, String authCode, String email){
Log.d("APP", authCode);
GoogleTokenRequest googleTokenRequest = new GoogleTokenRequest();
googleTokenRequest.setTokenId(idToken);
googleTokenRequest.setAuthCode(authCode);
googleTokenRequest.setEmail(email);
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<GoogleTokenRequest> call = apiService.sendTokenToBackend(googleTokenRequest);
Log.d("APP", call.toString());
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
call.enqueue(new Callback<GoogleTokenRequest>() {
//execute za sinhroni klic, enqueue za asinhroni
#Override
public void onResponse(Call<GoogleTokenRequest> call, Response<GoogleTokenRequest> response) {
String access_token = response.headers().get("Authorization");
Log.d("APP", access_token);
prefs.edit().putString("access_token",access_token).commit();
int statusCode = response.code();
if (statusCode == 206) {
SetPasswordFragment registerFragment = new SetPasswordFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_login_container, registerFragment);
fragmentTransaction.commit();
}
else{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
This is my fragment code:
public class SetPasswordFragment extends Fragment {
private OnSetPasswordListener onSetPasswordListener;
public SetPasswordFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnSetPasswordListener) {
onSetPasswordListener = (OnSetPasswordListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
LayoutInflater lf = getActivity().getLayoutInflater();
View rootView = lf.inflate(R.layout.fragment_set_password, container, false);
Button setPasswordButton = (Button) rootView.findViewById(R.id.btn_set_password_ok);
TextView textView = (TextView) rootView.findViewById(R.id.set_password_message);
Log.d("APP",rootView.toString());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String username = prefs.getString("username", "User");
textView.setText(String.format(getString(R.string.set_password_message), username));
setPasswordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setPasswordValidate();
}
});
return rootView;
}
this is the logcat:
This should probably fix it :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_set_password, container, false);
return rootView;
}
#Override
public void onViewCreated(View view){
Button setPasswordButton = (Button) view.findViewById(R.id.btn_set_password_ok);
TextView textView = (TextView) view.findViewById(R.id.set_password_message);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String username = prefs.getString("username", "User");
textView.setText(String.format(getString(R.string.set_password_message), username));
setPasswordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setPasswordValidate();
}
});
}
Note : I dont rexactly remember the exact parameters for the onViewCreated method but view is definitely there. So I guess this should work.
I know my problem description does not point to the real problem that I found but still I will post it since maybe it will help someone. I my case it was problem in xml file I just removed android:fillViewport="true" or set it to false and it works.
I have an activity and a fragment inside it.inside fragment, there is a button, and on click of button a dialog shows.
Everything works, until user do a orientation change and click button after it.
IllegalStateException(cannot perform this action after onsaveinstancestate) occurs when user clicks button after orientation change. I'm using android support framework.
Anybody have any idea regarfing this?
Activity Code
public void openMoreDialog(String shareData, String link) {
DialogFragment dialog = new MoreDialog(shareData, link);
dialog.show(getSupportFragmentManager(), "MoreDialog");
}
Fragment Code
public void onAttach(Activity activity) {
super.onAttach(activity);
mControl = (ActivityControl)activity;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ImageButton moreButton = (ImageButton)v.findViewById(R.id.moreButton);
moreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mControl.openMoreDialog(shareData, link);
}
});
return rootView;
}
FragmentDialog code
public class MoreDialog extends DialogFragment {
private String mShareData;
private String mLink;
public MoreDialog(String shareData, String link){
mShareData = shareData;
mLink = link;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.more_dialog, null);
Button openBtn = (Button)dialogView.findViewById(R.id.openBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openLink(mLink);
}
});
Button shareBtn = (Button)dialogView.findViewById(R.id.shareBtn);
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
shareNews(mShareData);
}
});
builder.setView(dialogView);
return builder.create();
}
private void openLink(String link){
}
private void shareNews(String data){
}
}
Helpful link & solution how to:
https://stackoverflow.com/a/17413324/619673 and btw, constructor in fragment must be empty! Documentation:
http://developer.android.com/reference/android/app/Fragment.html
public Fragment ()
Added in API level 11
Default constructor.
Every fragment must have an empty constructor, so
it can be instantiated when restoring its activity's state. It is
strongly recommended that subclasses do not have other constructors
with parameters, since these constructors will not be called when the
fragment is re-instantiated; instead, arguments can be supplied by the
caller with setArguments(Bundle) and later retrieved by the Fragment
with getArguments().
Applications should generally not implement a constructor. The first
place application code an run where the fragment is ready to be used
is in onAttach(Activity), the point where the fragment is actually
associated with its activity. Some applications may also want to
implement onInflate(Activity, AttributeSet, Bundle) to retrieve
attributes from a layout resource, though should take care here
because this happens for the fragment is attached to its activity.