DialogFragment not floating, acts embeded or as another fragment - android

I have this app, that I created a custom dialog for. I must of goofed something up cause while the .show call on the dialog does indeed bring it up, it looks like a whole new fragment and it is not floating but instead replacing the ui with its contents. I did see in their help for DialogFragment:
http://hi-android.info/docs/reference/android/app/DialogFragment.html#Lifecycle
that one can embed a dialog as a regular fragment or not. Though I am not doing anything to do this so I cannot figure out why its acting like an embedded fragment and not floating. After thinking on it, is it the way I defined my XML definition? The dialogfragment example above didn't really give a definition for the xml layout, so maybe that is where my issue is? (Even added the gravity to the xml file, still no dice)
My xml definition for this Dialog is here:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="20sp"
android:text = "Location:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"/>
<Spinner
android:id="#+id/location_spinner"
android:layout_width = "450sp"
android:layout_height="wrap_content"/>
<!-- fill out the data on the package total cost etc -->
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/location_dlg_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Okay"/>
<Button android:id="#+id/location_dlg_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"/>
<Button android:id="#+id/location_dlg_new"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create new..."/>
</LinearLayout>
</LinearLayout>
Like I said displays just fine, the code for the fragment:
package com.viciousbytes.studiotab.subactivities.dialogfragments;
import ... ...
public class LocationPicker extends DialogFragment {
ArrayList<Location> mLocations;
public static LocationPicker newInstance()
{
LocationPicker loc = new LocationPicker();
return loc;
}
private void setLocations(ArrayList<Location> loc)
{
mLocations=loc;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Pick a style based on the num.
int style = DialogFragment.STYLE_NORMAL, theme = android.R.style.Theme;
setStyle(style, theme);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.location_dialog, container, false);
Spinner spinner = (Spinner)v.findViewById(R.id.location_spinner);
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(v.getContext(), android.R.layout.simple_spinner_item, mLocations);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
if(mLocations==null)
spinner.setPrompt("No Locations");
else
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new LocationSelectedListener());
// Watch for button clicks.
Button newBtn = (Button)v.findViewById(R.id.location_dlg_new);
newBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
//create new start that activity...
}
});
// Cancel do nothing dismissthis
Button cancelBtn = (Button)v.findViewById(R.id.location_dlg_cancel);
cancelBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
//create new start that activity...
}
});
// okay button means set listener with the selected location.
Button okBtn = (Button)v.findViewById(R.id.location_dlg_ok);
okBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
//create new start that activity...
}
});
return v;
}
}
It is called from a fragment itself? though does that matter? because I am calling a TimePIckerDialog and a DatePickerDialog and those work fine, but my calling code from my other fragment is:
void showLocationDialog() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("locpicker");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = LocationPicker.newInstance();
newFragment.show(ft, "locpicker");
}

Your constructors are wrong. Try to have just one static method newInstance to instantiate the fragment for all cases and use a Bundle to store the arguments that you want to use in the fragment. Refer to Basic Dialog section here and extend it to your case.

Related

Trouble editing TextView within Fragment

So I am still fairly new to working with Android Studio and everything in it. I have been stuck on trying to get fragments to communicate directly with each other. Here I'm simply just trying to set the TextView text element within one of my fragments. I have looked for hours and tried a lot, but I'm not sure what to do. Also, I am implementing my fragments through code in a FrameLayout.
Here is my fragment whose text value I'm trying to edit:
public class ReceivingFrag extends Fragment {
TextView sender;
public void updateText(String text) {
sender.setText(text);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_sender, container, false);
sender = (TextView) v.findViewById(R.id.sender);
return v;
}
}
I believe my root problem is that getView() and sender both return Null. I also understand that fragments are not technically views, but rather aid in the layout of views and ViewGroups. Any help is appreciated.
Not sure if it helps, but this is the method that calls the updateText() method within the ReceivingFrag class.
public void sendText(String text){
ReceivingFrag frag = new ReceivingFrag();
getSupportFragmentManager().beginTransaction().add(R.id.receiving_container, frag).commit();
getSupportFragmentManager().executePendingTransactions()
frag.updateText(text);
}
**Edit:
This is my MainActivity class that is calling and creating the Fragment:
public class MainActivity extends AppCompatActivity implements SendingFragment.TextClicked {
private static final String TAG = MainActivity.class.getSimpleName();
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] myStringArray = {"Hello", "Nice To See You", "Bye"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myStringArray);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
sendText("Hello");
}
#Override
public void sendText(String text){
ReceivingFrag frag = new ReceivingFrag();
getSupportFragmentManager().beginTransaction().add(R.id.receiving_container, frag).commit();
getSupportFragmentManager().executePendingTransactions();
frag.updateText(text);
}}
**Edit 2:
This is the MainActivity layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/tools"
xmlns:tools2="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
android:layout_weight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="#string/button_send"/>
</LinearLayout>
<ListView android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#+id/receiving_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></FrameLayout></LinearLayout>
And this is the layout for the Fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/sender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/frag_sender"
android:background="#color/gray"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/></LinearLayout>
Solution:
So as mentioned below, the runtime error was fixed by adding
#Override
protected void onResume() {
super.onResume();
sendText("hello");
}
to the MainActivity class. After reading from https://developer.android.com/guide/components/fragments.html#Lifecycle
I think the statement
"Once the activity reaches the resumed state, you can freely add and remove fragments to the activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment change independently."
best explains the situation and why the error initially occurred.
If you instead put the sendText() in your onResume() like this,
#Override
protected void onResume() {
super.onResume();
sendText("Hello");
}
It will not give you the Null Pointer Exception. The fragment is still null when you call on it from onCreate().
Change your Fragment to this:
public class ReceivingFrag extends Fragment {
private TextView sender;
public void updateText(String text) {
sender.setText(text);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_sender, container, false);
sender = (TextView) v.findViewById(R.id.sender);
return v;
}
}
and in your activity, before calling the updateText method, make sure the fragment transaction has executed by doing:
public void sendText(String text){
ReceivingFrag frag = new ReceivingFrag();
getSupportFragmentManager().beginTransaction().add(R.id.receiving_container, frag).commit();
getSupportFragmentManager().executePendingTransactions();
frag.updateText(text);
}

Android construct for chaining fragments together

I'm looking to create a small flash card type element for my app. I've looked at several solutions namely the FragmentStatePagerAdapter and it's parent the FragmentPagerAdapter. Neither of these solve the problem I want to solve. They deal with listviews of fragments. I want to have a list of fragments that when I hit a button I move to the next one fragment in the list until I'm all done.
I've got all the saving the data part of it solved. I just cannot figure out how to chain my fragments together.
To be explicit, what I'm looking for is:
a->b->c->d->done and go back to activity or a finished fragment.
The user would obviously use a button to progress from fragment to fragment.
I chose fragments because I figured that would be the easiest. I'm not opposed to activities, but my problem is still largely the same.
I've tried implementing the FragmentPager stuff, but as I said it didn't suite my needs.
How dynamic are the fragments you are making? If there's a set amount of interchangeable elements, you can try creating a delegate function in your main activity that opens fragments depending on a set of parameters. Better still, you make your fragments modular so that you only have a few fragments with different states based on what you give them.
public void onCardWithIdSelected(int id, String param1, String param2, ...) {
Fragment fragment = NULL;
if(id == 0) {
fragment = cardFragment.newInstanceFromParams(param1, param2, ...); //this will pass the parameters onto the desired fragment
}
else if(id == 1) {
fragment = cardFragment.newInstanceFromParams(param1, param2, ...); //this will pass the parameters onto the desired fragment
}
else if(id == 2) {
fragment = cardFragment.newInstanceFromParams(param1, param2, ...); //this will pass the parameters onto the desired fragment
}
//and so on...
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null); //only do this if you don't want users to be able to go back
// Commit the transaction
transaction.commit();
}
Then whenever you want to move to a different fragment from one, you just call this function on the main activity with your desired parameters.
I figured out how to do this with a rather simple solution:
I have my activity which has some variables so that it knows what fragment it is on, along with that it inflates a layout with a framelayout and uses fragmentmanager transactions to replace given the fragment number we are on. Then I have a parcelable class that defines the flashcard that is passed to each fragment upon instantiation. On the activity's layout I have 3 buttons, "check", "correct", "incorrect" which, using View.GONE/View.VISIBLE am able to give the UI experience I want. On the click of the "correct"/"incorrect" we start a transaction and move down the list to the next card.
The code:
/**
* The activity
*/
public class VocabTestActivity extends Activity {
private int mWordsCorrect = 0;
private int mWordsIncorrect = 0;
private int mCurrentPosition = 0;
private ArrayList<Fragment> mCards = new ArrayList<Fragment>();
private final int FLAG_TOTAL_CARDS = 5;
private GrammarDataSource mDataSource;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practice);
final Button buttonCheck = (Button) findViewById(R.id.buttonCheckWordPractice);
final Button buttonCorrect = (Button) findViewById(R.id.buttonCorrectWordPractice);
final Button buttonIncorrect = (Button) findViewById(R.id.buttonIncorrectWordPractice);
final TextView textViewProgressBar = (TextView) findViewById(R.id.textViewProgressBarPractice);
this.mDataSource = new GrammarDataSource(this);
this.initializeCards();
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonCheck.setVisibility(View.GONE);
buttonCorrect.setVisibility(View.VISIBLE);
buttonIncorrect.setVisibility(View.VISIBLE);
}
});
buttonCorrect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mWordsCorrect++;
getFragmentManager().beginTransaction().replace(
R.id.practice_frame,
mCards.get(mCurrentPosition++)
).commit();
buttonCheck.setVisibility(View.VISIBLE);
buttonCorrect.setVisibility(View.GONE);
buttonIncorrect.setVisibility(View.GONE);
textViewProgressBar.setText(getString(R.string.practice_progress_bar, mCurrentPosition, FLAG_TOTAL_CARDS));
}
});
buttonIncorrect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mWordsIncorrect++;
getFragmentManager().beginTransaction().replace(
R.id.practice_frame,
mCards.get(mCurrentPosition++)
).commit();
buttonCheck.setVisibility(View.VISIBLE);
buttonCorrect.setVisibility(View.GONE);
buttonIncorrect.setVisibility(View.GONE);
textViewProgressBar.setText(getString(R.string.practice_progress_bar, mCurrentPosition, FLAG_TOTAL_CARDS));
}
});
}
private void initializeCards() {
for(VocabWord v : this.mDataSource.selectFlashCards(FLAG_TOTAL_CARDS)) {
VocabTestFragment frag = VocabTestFragment.newInstance(new ParcelableWord(v));
mCards.add(frag);
}
}
}
/**
* The fragment
*/
public class VocabTestFragment extends Fragment {
private ViewGroup mRoot;
public final String TAG = getClass().getSimpleName();
private VocabWord mWord;
public static VocabTestFragment newInstance(ParcelableWord w) {
VocabTestFragment frag = new VocabTestFragment();
Bundle args = new Bundle();
args.putParcelable("word", w);
frag.setArguments(args);
return frag;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.mRoot = (ViewGroup) inflater.inflate(R.layout.fragment_practice_vocab, container, false);
ItalianWord word = null;
ParcelableWord pw = getArguments().getParcelable("word");
pw.printIt();
word = (ItalianWord) pw.getWord();
TextView tv = (TextView) this.mRoot.findViewById(R.id.word);
if(word != null) {
tv.setText(word.getmId() + " is the id\t" + word.getmWord());
} else {
tv.setText("Word not provided");
}
return this.mRoot;
}
}
/**
* fragment_practice_vocab
*/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#android:drawable/gallery_thumb"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/word"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="placeholder"
android:layout_weight="4" />
</LinearLayout>
/**
* practice_activity
*/
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewProgressBarPractice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/practice_progress_bar"
/>
<FrameLayout
android:id="#+id/practice_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewProgressBarPractice"
>
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="end"
android:layout_alignParentBottom="true"
>
<Button
android:id="#+id/buttonCheckWordPractice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check"
/>
<Button
android:id="#+id/buttonCorrectWordPractice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:visibility="gone"
android:text="Correct"
/>
<Button
android:id="#+id/buttonIncorrectWordPractice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:visibility="gone"
android:text="Incorrect"
/>
</LinearLayout>
</RelativeLayout>

Invoking Fragment from a popup android

In my main activity layout,I have an image button.
On clicking it,a popup pops up.The layout of the popup is as follows.
test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100px"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#android:color/black">
<Button
android:padding="5dp"
android:id="#+id/b_help"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Help"
android:textColor="#android:color/white"
android:background="#android:color/black"/>
<Button
android:padding="5dp"
android:id="#+id/b_pref"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Preferences"
android:textColor="#android:color/white"
android:background="#android:color/black"/>
<Button
android:padding="5dp"
android:id="#+id/b_about"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="About Us"
android:textColor="#android:color/white"
android:background="#android:color/black"/>
</LinearLayout>
The popup is displayed by the following code from MainActivity.java
btnOpenPopup = (ImageButton)findViewById(R.id.menu_button);
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
popupWindow = new PopupWindow(getBaseContext());
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}});
The popup window class is as follows
PopupWindow.java
public class PopupWindow extends android.widget.PopupWindow implements View.OnClickListener{
Context ctx;
View popupView;
Button help,pref,about;
public PopupWindow(Context context)
{
super(context);
ctx = context;
popupView = LayoutInflater.from(context).inflate(R.layout.test, null);
setContentView(popupView);
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
// Closes the popup window when touch outside of it - when looses focus
setOutsideTouchable(true);
setFocusable(true);
// Removes default black background
setBackgroundDrawable(new BitmapDrawable());
pref = (Button)popupView.findViewById(R.id.b_pref);
pref.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.b_pref:break;
case R.id.b_help:break;
case R.id.b_about:break;
}
}
}
Now on clicking the preferences button in the popup,i need to display the preference fragment.
I tried this ,for setOnClickListener for the preference button,but it is not working as the popupwindow class cannot extend fragmentactivity and getFragmentManager() is not happening.
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
Prefs mPrefsFragment = new Prefs();
//this line..
setContentView(R.layout.activity_prefs);
mFragmentTransaction.replace(android.R.id.content, mPrefsFragment);
mFragmentTransaction.addToBackStack(null);
setContentView(R.layout.activity_main);
mFragmentTransaction.commit();
How can i invoke the preffragment using the button from popup??
Any help will be much appreciated.Cause I am badly stuck at this.
I would suggest you save a reference to the fragment manager you got as a variable in another situation, such as when you first started, and use that instead. Takes a little memory, but the context you are in will not effect how you get your manager then.

How to create a DialogFragment without title?

I'm creating a DialogFragment to show some help messages regarding my app. Everything works fine besides one thing: There is a black stripe at the top of the window that shows the DialogFragment, that I presume is reserved for the title, something I don't want to use.
This is specially painful since my custom DialogFragment uses a white background, so the change is way too notorious to be left aside.
Let me show you this in a more graphical manner:
Now the XML code for my DialogFragment is as follows:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/holding"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/dialog_fragment_bg"
>
<!-- Usamos un LinearLayout para que la imagen y el texto esten bien alineados -->
<LinearLayout
android:id="#+id/confirmationToast"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView android:id="#+id/confirmationToastText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="#string/help_dialog_fragment"
android:textColor="#AE0000"
android:gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/confirmationButtonLL"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<Button android:id="#+id/confirmationDialogButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginBottom="60dp"
android:background="#drawable/ok_button">
</Button>
</LinearLayout>
</LinearLayout>
</ScrollView>
And the code of the class that implements the DialogFragment:
public class HelpDialog extends DialogFragment {
public HelpDialog() {
// Empty constructor required for DialogFragment
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the XML view for the help dialog fragment
View view = inflater.inflate(R.layout.help_dialog_fragment, container);
TextView text = (TextView)view.findViewById(R.id.confirmationToastText);
text.setText(Html.fromHtml(getString(R.string.help_dialog_fragment)));
//get the OK button and add a Listener
((Button) view.findViewById(R.id.confirmationDialogButton)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
HelpDialog.this.dismiss();
}
});
return view;
}
}
And the creation process in the main Activity:
/**
* Shows the HelpDialog Fragment
*/
private void showHelpDialog() {
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
HelpDialog helpDialog = new HelpDialog();
helpDialog.show(fm, "fragment_help");
}
I really don't know if this answer, related with a Dialog, fits here also Android: How to create a Dialog without a title?
How can I get rid of this title area?
Just add this line of code in your HelpDialog.onCreateView(...)
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
This way you're explicitly asking to get a window without title :)
EDIT
As #DataGraham and #Blundell pointed out on the comments below, it's safer to add the request for a title-less window in the onCreateDialog() method instead of onCreateView(). This way you can prevent ennoying NPE when you're not using your fragment as a Dialog:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
Dialog fragment has setStyle method, which should be called before view creation Java Doc. Also style of the dialog can be set with the same method
public static MyDialogFragment newInstance() {
MyDialogFragment mDialogFragment = new MyDialogFragment();
//Set Arguments here if needed for dialog auto recreation on screen rotation
mDialogFragment.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
return mDialogFragment;
}
FragmentManager manager = getSupportFragmentManager();
SettingsDialog sd = new SettingsDialog();
sd.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
sd.show(manager, "settings_dialog");
Try easy way
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, 0);
}
Set the style to Theme_Holo_Dialog_NoActionBar:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, android.R.style.Theme_Holo_Dialog_NoActionBar);
}
public class LoginDialog extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_dialog, null);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
}
I could not get the suggested methods to work when using a androidx.preference.PreferenceDialogFragmentCompat.
What ultimately worked was adding the following method to the PreferenceDialogFragmentCompat:
/**
* This is needed to get a dialog without a title.
*/
#Override
protected void onPrepareDialogBuilder(#NonNull AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
builder.setTitle(null);
}

How to add layouts to dialog

I have an idea in mind but im not sure about how to implement it
first i have a dialog
final Dialog dialog = new Dialog(mContext);
i also have a layout
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textViewDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textViewWhen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
what i want is to add this layout in the dialog, i may also want to add more of the same layout right under it inside that dialog
how can i do that?
for example how can i add two of this layout in one dialog?
something like
Dialog Title
Large Text
Small Text
Medium Text
Large Text
Small Text
Medium Text
Something like this:
LayoutInflater li = LayoutInflater.from(SomeActivity.this);
someLayout = (LinearLayout)li.inflate(R.layout.some_layout, null);
alert = new AlertDialog.Builder(SettingsActivity.this);
alert.setView(someLayout);
This is an example from my application:
public class ConfirmDialog extends DialogFragment {
public static String TAG = "Confirm Dialog";
public interface ConfirmDialogCompliant {
public void doOkConfirmClick();
public void doCancelConfirmClick();
}
private ConfirmDialogCompliant caller;
private String message;
public ConfirmDialog(ConfirmDialogCompliant caller, String message){
super();
this.caller = caller;
this.message = message;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.confirm_dialog, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
((TextView) view.findViewById(R.id.textview_confirm)).setText(message);
((Button) view.findViewById(R.id.ok_confirm_button)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
caller.doOkConfirmClick();
}
});
((Button) view.findViewById(R.id.cancel_confirm_button)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
caller.doCancelConfirmClick();
}
});
return view;
}
}
where the inflated layout is confirm_dialog.xml.
You inflate your layout in the onCreateView method.
In this case I used DialogFragment (which I suggest you to use...see the support library so that you don't have to worry about your target SDK) but the same applies to Dialog.
Hope it helps you!
You can check this documentation page which explain how to add a custom layout on dialog
http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog
The key is the setContentView method:
dialog.setContentView(R.layout.custom_dialog);
Check out this one :
how to get customized alert dialog , like the one shown in image?
Refer the answer which I've given (Aamir Shah)
Use a DialogFragment, which allows you to, just like any other Fragment, completely customize the layout. It is available in the v4 support library.
http://developer.android.com/reference/android/app/DialogFragment.html
http://developer.android.com/tools/extras/support-library.html

Categories

Resources