UI of fragment not getting displayed - android

I'm trying to call a fragment from my activity. The onCreate and onCreateView methods are being called. However, the UI for the fragment is not being displayed. I don't see any errors in logcat either.
Basically this is what I want to do. Upon clicking the imagebutton in activity.xml, I call the fetchNotifications() method, which in turn calls an asynctask to do some work and then call my fragment. In my fragment, I create a dynamic listview containing multiple textviews.
Here are my codes:
activity_home_screen.xml (my activity layout):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:src="#drawable/read_msg"
android:onClick="fetchNotifications"/>
</RelativeLayout>
HomeScreen.java (my activity class):
public class HomeScreen extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
}
//Method called from button onClick
public void fetchNotifications(View view){
new FetchNotifications().execute("http://x.x.x.x:9000/Android/homescreen/ruby");
}
private class GetNotifications extends AsyncTask<String, String, String>{//some code here}
private class FetchNotifications extends AsyncTask<String, String, String>{
FragmentManager fm;
#Override
protected String doInBackground(String... params) {
try {
URL notifications = new URL(params[0]);
//JSONObject notificationsJSON = new JSONObject(getResponse(notifications).toString());
JSONObject notificationsJSON = new JSONObject(globals.JSONS.NOTIFICATIONS);
if(notificationsJSON!=null){
Globals globals = Globals.getInstance();
globals.setReplyString(notificationsJSON.getJSONArray("notification").toString());
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(new DisplayNotifications(), "Notification");
ft.commit();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public StringBuilder getResponse(URL url){//some code here}
}
activity_display_notifications.xml (my fragment_layout):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.buildingcustomadapter.MainActivity"
tools:ignore="MergeRootFrame">
<ListView
android:id="#+id/notifications_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</FrameLayout>
single_notification.xml (contains textview which will be added to the listview):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/notification_TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
And finally my fragment class (DisplayNotifications.java):
package com.example.projectswipe;
import globals.Globals;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DisplayNotifications extends Fragment {
Globals global;
JSONArray notificationsArray;
ArrayList<String> notification = new ArrayList<String>();
ListView l;
public DisplayNotifications() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
Log.d("Test", "onCreate >>>>>>>>");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_display_notifications, container, false);
Log.d("Test", "onCreateView >>>>>>>>");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
try {
global = Globals.getInstance();
notificationsArray = new JSONArray(global.getReplyString());
System.out.println(">>>>>>>>>>"+notificationsArray);
for(int i=0; i<notificationsArray.length(); i++){
notification.add(notificationsArray.getJSONObject(i).getString("msg"));
}
} catch (JSONException e) {
e.printStackTrace();
}
l = (ListView) getView().findViewById(R.id.notifications_listView);
NotificationsAdapter adapter = new NotificationsAdapter(getActivity(), notification);
Log.d("Test", "onActivityCreated >>>>>>>>");
l.setAdapter(adapter);
//l.setOnItemClickListener(this);
//l.setEmptyView(getActivity().findViewById(R.id.emptyProductDeals));
}
}
class NotificationsAdapter extends ArrayAdapter<String>{
Context contex;
ArrayList<String> notifications;
/*
* Create a constructor which calls super(). In super(), we pass context, the singlerow.xml file, and the datasource
*/
NotificationsAdapter(Context c, ArrayList<String> notifications){
super(c, R.layout.single_notification, notifications);
this.contex = c;
this.notifications = notifications;
}
class MyViewHolder{
TextView notification;
MyViewHolder(View v){
notification = (TextView) v.findViewById(R.id.notification_TextView);
}
}
public View getView(int position, View convertView, ViewGroup parent){
View root = convertView;
MyViewHolder holder = null;
if(root==null)
{
LayoutInflater inflater = (LayoutInflater) contex.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
root = inflater.inflate(R.layout.single_notification, parent, false);
holder = new MyViewHolder(root);
root.setTag(holder);
}
else{
holder = (MyViewHolder) root.getTag();
}
holder.notification.setText(notifications.get(position));
return root;
}
}
What am I doing wrong here? I know I'm missing something really basic, but I've been stuck at this thing for hours.
Thanks.

First, your main layout doesn't include a container (usually a FrameLayout) for your fragment and your FragmentTransaction doesn't specify where the fragment view must be attached. The add() method which doesn't take a containerViewId as parameter is reserved for fragments without a user interface, that's why you don't see anything.
Second, you can't call the FragmentManager from a background thread like you do here. It must always be done on the UI thread. If you use an AsyncTask, it means the FragmentTransaction must be done in onPostExecute() and not in doInBackground(). However, make sure your activity is started before you try to commit the fragment transaction or you will get an IllegalStateException. A common way to do this is to cancel the AsyncTask in onStop(), so onPostExecute() won't be called after onStop().
Other potential problems in your code:
Never set the height of a ListView to wrap_content. It may cause glitches and performance problems. Use match_parent, a fixed height, or a weight instead.
Pass the data that your Fragment will show in its Arguments Bundle, or make the Fragment load its own data when it is shown, instead of loading the data in some global variable that your fragment will access later on. Your Fragment cannot rely on the fact that the global variable will be properly set when it starts because the system may kill your application at any moment when it's not visible and restore it later. When the application is restored, the Activity, the Fragment and its arguments bundle will be restored as well, but your global variable will not.

Related

having trouble with TabLayout using fragments and JSON

Hi I been trying for a while to figure this out and checked a lot of post. I am having this problem when I switch to a new tab only the XML layout is showing. Though when I start on the first tab and fragment the json content shows up how I like. I am not sure how to get the json content to change for a new tab.
Fragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Random;
/**
* A simple {#link Fragment} subclass.
*/
public class TVFragment extends Fragment {
public TVFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tv_activity, container, false);
ArrayList<String> media = new ArrayList<String>();
media.add("movie1");
media.add("movie2");
media.add("movie3");
this.loadMovieInfo(media);
// loadMoviePoster(media);
return rootView;
}
private void loadMovieInfo(ArrayList<String> media) {
Random random = new Random();
int x = (int) random.nextInt(media.size()) * 1;
//Use Ion to get json info for movie from movie/tv api.
Ion.with(this)
.load("http://www.omdbapi.com/?t=" + media.get(x)
+ "&apikey0000")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
// create json object
JSONObject json = new JSONObject(result);
//get json title and poster from the json object.
String name = json.getString("Title");
String urlString = json.getString("Poster");
//get TextView to display title
TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
mediaName.setText(name);
/* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
*/
new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);
} catch (JSONException jsone) {
Log.wtf("Json Import problems", jsone);
}
}
});
}
}
MainActivity
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
/**
* Created by Samuel on 2/12/2018.
*/
public class TechnologyResultsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the tv_activitylayout file
setContentView(R.layout.tab_viewpager_activity);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
MediaTypeAdapter adapter = new MediaTypeAdapter(getSupportFragmentManager(),getApplicationContext());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
Adapter
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by Samuel on 2/14/2018.
*/
public class MediaTypeAdapter extends FragmentPagerAdapter {
public MediaTypeAdapter(FragmentManager fragmentManager, Context applicationContext){
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new TVFragment();
} else if (position == 1) {
return new MovieFragment();
}
else {
return new MovieFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0){
return "TV";
} else {
return "MOVIES";
}
}
}
tablayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
movie_activity layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom"
android:paddingBottom="16dp">
<ImageView
android:id="#+id/poster"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:src="#drawable/poster"
android:layout_weight="1"
/>
<ScrollView
android:id="#+id/synopsis_scroll"
android:layout_width="match_parent"
android:layout_height="81dp"
android:padding="8dp">
<TextView
android:id="#+id/synopsis_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="Academy Award nominee, heart-warming, hit comedy from producer Judd Apatow (Bridesmaids and Trainwreck). The Big Sick is based on the real-life courtship between Pakistan-born comedian Kumail Nanjiani (Nanjiani) and grad student Emily Gordon (Zoe Kazan) who fall in love but struggle while dealing with Emily's mysterious illness and their families culture clash. Also staring Ray Romano and Holly Hunter. Included with Prime."/>
</ScrollView>
</LinearLayout>
</LinearLayout>
you have to create a new class moviefragment and have to write code to fetch movies in that.
public class MovieFragment extends Fragment{
TechnologyResultsActivity technology;
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
technology= (TechnologyResultsActivity) context;
}
public static Fragment newInstance(Bundle bundle){
MovieFragment movie=new MovieFragment();
if(bundle!=null){
movie.setArguments(bundle);
}
return movie;
}
#Override
public void onResume() {
super.onResume();
// this will only called when fragment is visible to user
if(isVisible()) {
if (Constant.isInternetConnected(homeActivity)) {
ArrayList<String> media = new ArrayList<String>();
media.add("movie1");
media.add("movie2");
media.add("movie3");
loadMovieInfo(media)
} else {
Toast.makeText(homeActivity, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
}
private void loadMovieInfo(ArrayList<String> media) {
Random random = new Random();
int x = (int) random.nextInt(media.size()) * 1;
//Use Ion to get json info for movie from movie/tv api.
Ion.with(this)
.load("http://www.omdbapi.com/?t=" + media.get(x)
+ "&apikey0000")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
try {
// create json object
JSONObject json = new JSONObject(result);
//get json title and poster from the json object.
String name = json.getString("Title");
String urlString = json.getString("Poster");
//get TextView to display title
TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
mediaName.setText(name);
/* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
*/
new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);
} catch (JSONException jsone) {
Log.wtf("Json Import problems", jsone);
}
}
});
}
}

Buttons within a ListFragment not clickable

I have an Activity that lays out ListFragments side by side (as many as a user wants) in a HorizontalScrollView upon choosing an option in the ActionBar.
Each ListFragment item contains TextViews and a Button. A SimpleAdapter populates data for each item in every ListFragment.
The issue I am facing now is that the buttons in each list item do not respond to clicks. The layout can be summarized as follows: Button inside a ListFragment inside a FragmentActivity, going from the innermost child element to the parent at the root view.
I have spent many hours on this problem and I am unable to arrive at a solution to make the buttons respond to clicks. Some of the approaches I have used include obtaining the button's view and attaching onClickListeners, 2) implementing the OnClickListener interface for the ListFragment. I am also aware of the onInterceptTouchEvent method for a ViewGroup class, however my lack of experience with Android prevents me from arriving at a solution. Any guidance or direction towards solving this problem would be most appreciated.
Here is the code for the ListFragment:
package com.example.androidlistfragmenttest;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SimpleAdapter;
public class MyFragment extends ListFragment {
private ArrayList<HashMap<String,String>> arraylist;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_layout, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
//THIS DOES NOT PRINT IN LOGCAT. BUTTON DOES NOT RESPOND TO CLICKS.
#Override
public void onClick(View arg0) {
Log.v("GODZILLA","ATOMIC BREATH");
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
arraylist = dataGenerator();
SimpleAdapter adapter = new SimpleAdapter(getActivity().getApplicationContext(), arraylist, R.layout.fragment_layout,new String[]{"KEY"},new int[]{R.id.text_id});
setListAdapter(adapter);
}
/*
* Method to populate an adapter's data list.
*/
public ArrayList<HashMap<String,String>> dataGenerator(){
HashMap<String,String> hashMap1 = new HashMap<String,String>();
hashMap1.put("KEY", "A");
HashMap<String,String> hashMap2 = new HashMap<String,String>();
hashMap2.put("KEY", "B");
HashMap<String,String> hashMap3 = new HashMap<String,String>();
hashMap3.put("KEY", "C");
HashMap<String,String> hashMap4 = new HashMap<String,String>();
hashMap4.put("KEY", "D");
HashMap<String,String> hashMap5 = new HashMap<String,String>();
hashMap5.put("KEY", "E");
ArrayList<HashMap<String,String>> arraylist = new ArrayList<HashMap<String,String>>();
arraylist.add(hashMap1);
arraylist.add(hashMap2);
arraylist.add(hashMap3);
arraylist.add(hashMap4);
arraylist.add(hashMap5);
return arraylist;
}
} //End of MyFragment
And this is the code for the Activity containing the Fragment(s):
package com.example.androidlistfragmenttest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity {
private Stack<String> tagStack;
private Integer last_tag_number;
public MainActivity(){
last_tag_number = new Integer("0");
tagStack = new Stack<String>();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_fragment:
addColumn();
return true;
case R.id.remove_column:
removeColumn();
return true;
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
/*
* This method adds a fragment to the screen
*/
public void addColumn(){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_activity, fragment,tagGenerator());
fragmentTransaction.commit();
}
/*
* This method removes a fragment from the screen
*/
public void removeColumn(){
if(tagStack.size() != 0){
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tagStack.pop());
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
}
}
/*
* This function generates tags for each fragment that is displayed on the screen
* The tags pose as unique identifiers for each fragment
*/
public String tagGenerator(){
Integer tag_number;
if(last_tag_number.intValue() == 0){
tag_number = last_tag_number;
int temp = last_tag_number.intValue();
temp+=1;
last_tag_number = Integer.valueOf(temp);
}
else{
tag_number = new Integer(last_tag_number.intValue());
int temp = last_tag_number.intValue();
temp+=1;
last_tag_number = Integer.valueOf(temp);
}
String tag = tag_number.toString();
tagStack.push(tag);
return tag;
}
} //End of MainActivity
As well as the layouts for the FragmentActivity:
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:id="#+id/fragment_activity"
android:layout_width="fill_parent"
android:layout_height = "fill_parent"
android:orientation = "horizontal"
android:gravity="center"
>
</LinearLayout>
</HorizontalScrollView>
And the ListFragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
android:layout_margin="5dp"
android:descendantFocusability="blocksDescendants" >
<ListView android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_gravity="center" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/label"
android:layout_gravity="start"
/>
<TextView
android:id="#+id/text_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="end"
/>
</LinearLayout>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal" >
<Button
android:id="#+id/button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/button"
android:layout_margin="2dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
/>
</LinearLayout>
</LinearLayout>
The problem is that the ListItem is consuming the click and it is not getting passed to the button below.
You need to set the list items to inactive and handle the clicks yourself. In your custom Adapter add the following methods to disable the items (They override methods from BaseAdapter):
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return false;
}
Edit: Here is a related question that may offer a better solution, it depends on your design.

Access a method of a Fragment from the ViewPager Activity

I have a Fragment with a method setName() that changes an EditText text, by means of the setText function.
What is the best way to call that method from the activity that hosts that fragment by means of a ViewPager?
In other words, how can I access a Fragment's methods (which change that fragment's layout, for example) from the Activity that hosts that fragment by means of a ViewPager?
I am asking this because I have tried several ways, but always with errors.
Best way to do this, just call
CallingFragmentName fragment = (CallingFragmentName) viewPager
.getAdapter()
.instantiateItem(viewPager, viewPager.getCurrentItem());
It will re-instantiate your calling Fragment, so that it will not throw null pointer exception.
I know this is a little late, but I ran into the same problem and maybe it will help others if you already solved it.
The first problem I found with ViewPager is that it is almost impossible to get a reference to a fragment. The fragments are created dynamically in getItem() and therefore you can't set an ID and they are automatically re-taged by the swicher, so you can't find it by tag either. There are some ways out there to do it, but they are all workarounds. (Update data in ListFragment as part of ViewPager)
The way I solved it was using essentially a double Callback. Fragment A has an interface implemented by the Main Activity, the Main Activity has a interface implemented by Fragment B. On e.g. a button clink in Fragment A the callback function in Main Activity is called, which than in turn calls the callback in Fragment B. Look at the code below. I hope I posted everything and it will help. btw, I have only tried this with a ViewPager, but I assume it would work with any sort of Fragment communication.
Main Avtivity java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements FragmentA.Caller {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
PassCallToB passOnToB = null;
FragmentManager myManager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
MyManager = fm;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if(position == 0) {
fragment = new FragmentA();
} else if (position == 1) {
fragment = new FragmentB();
passOnToB = (PassCallToB)fragment;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Frag A";
case 1:
return "Frag B";
}
return null;
}
public void setCallback() {
List<Fragment> frags = myManager.getFragments();
for(Fragment fragment : frags) {
if(fragment instanceof FragmentB){
passOnToB = (PassCallToB)fragment;
}
}
}
}
public interface PassCallToB {
public void passItOn();
}
#Override
public void CallB() {
if(passOnToB instanceof Fragment)
passOnToB.passItOn();
else {
mSectionsPagerAdapter.setCallback();
passOnToB.passItOn();
}
}
}
Main Activity xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
Fragment A java:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class FragmentA extends Fragment {
Button btnCallB = null;
Caller listener = null;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
btnCallB = (Button)rootView.findViewById(R.id.btnCallB);
btnCallB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
listener.CallB();
}
});
return rootView;
}
public interface Caller {
public void CallB();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof FragmentActivity) {
listener = (Caller) activity;
} else {
throw new ClassCastException(activity.toString() + " must implemenet listener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Fragment A xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="This is Fragment A" />
<Button
android:id="#+id/btnCallB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:text="Call Fragment B" />
</RelativeLayout>
Fragment B Java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class FragmentB extends Fragment implements MainActivity.PassCallToB {
public FragmentB() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
View rootView = inflater.inflate(R.layout.fragment_b, container, false);
return rootView;
}
#Override
public void passItOn() {
Toast.makeText(getActivity(), "Hello from B", Toast.LENGTH_SHORT).show();
}
}
Fragment B xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="This is Fragment B" />
</RelativeLayout>
You can access public methods within the fragments held by your ViewPager. You need to either (1) store a reference to the Fragment when you create it and add it to the list that will back your pager adapter or (2) you need to get a reference to the fragment from the pager adapter itself. For example:
Fragment fragmentA = null; //instance variable
fragmenA = new Fragment(); //whereever you instantiate your fragment
If your method is
public void setName(String args){
//do something
}
all you would do is call that method from the reference to the fragment held by your ViewPager
fragmentA.setName(args);
You pass whatever arguments you need just like calling a regular method. Note this ONLY works if you are calling a method within a fragment from its containing ViewPager or FragmentActivity. If you want to do the reverse, fragment to activity, you need to use an inerface.
Fragment
private static FragmentName instance;
public static synchronized FragmentName getInstance()
{
return instance;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance=this;
....
}
public void methodName()
{...}
Activity
FragmentName.getInstance().methodName();

How to implement Android Fragment Transaction .add syntax error

I'm would like to make my Android application use Fragment Transactions, so that I can
switch between various Fragments display their associated lists. My application
worked fine prior to attempting to convert to just Fragment Transactions. In my initial activity_main.xml,
I removed the android:name="com.birdsall.peter.chap.ChapterFragment", it is my understanding you can't use xml defined fragments
with fragment transactions.
1) I can't seem to get the .add() within
getSupportFragmentManager correct with it's parameters, even with code from a working example.
I have also attempted to use the newer version of FragmentTransactions to no avail.
I even took a working example of code using getSupportFragmentManager / FragmentTransactions,
modified to use the names I had, it worked. I then imported that code into my application
and it fails on the .add() syntax. I'm somewhat new to Android development and can't
pinpoint where I'm going wrong.
Here is my main xml layout for the FrameLayout
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="#+id/chapterfragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Removed this from above <fragment> block to enable Fragment Transaction
android:name="com.birdsall.peter.chap.ChapterFragment" -->
</LinearLayout>
Here is the xml layout for the ChapterFragment ListView
chapterfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView android:id="#+id/chapterlist" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentLeft="true" />
</RelativeLayout>
Here is the layout for the details of the list
chapter_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical" android:padding="6dip">
<TextView android:id="#+id/chapter1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView android:id="#+id/textViewLiteral" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/chapter1" android:text=" - "
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView android:id="#+id/chaptertitle1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textViewLiteral"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
Here is the MainActivity.java that I have modified. I left the 'setContentView(R.layout.activity_main);' as I thought I needed to create a view (even though it empty) to add the fragment view to.
package com.birdsall.peter.chap;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
public class MainActivity extends FragmentActivity implements ChapterFragment.ChapterSelectedListener {
private static final String TAG = "Main_Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Starting ...");
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
// Create an instance of ExampleFragment
ChapterFragment firstFragment = new ChapterFragment();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
**.add**(R.id.fragment_container, firstFragment).commit();
Log.i(TAG, "Ending ...");
}
} ...
Here is my ChapterFragment.java
package com.birdsall.peter.chap;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class ChapterFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
ChapterSelectedListener mCallback;
// Container Activity must implement this interface
public interface ChapterSelectedListener {
public void onChapterSelected(String position, int rowId);
}
public SimpleCursorAdapter dataAdapter;
private static final String TAG = "ChapterFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
View listview = inflater.inflate(R.layout.activity_main,null);
ListView mList =(ListView)listview.findViewById(R.id.chapterlist);
// The desired columns to be bound
String[] columns = new String[] {
TDAdb.COL_CHAPTER,
TDAdb.COL_CHAPTERTITLE};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.chapter1,
R.id.chaptertitle1,
};
// create an adapter from the SimpleCursorAdapter
dataAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.chapter_info,
null,
columns,
to,
0);
mList.setAdapter(dataAdapter);
//Ensures a loader is initialized and active.
getLoaderManager().initLoader(0, null, this);
return listview;
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, " onStart");
displayListView();
Log.i(TAG, " end of onStart");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (ChapterSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ChapterSelectedListener");
}
}
#Override
public void onResume() {
super.onResume();
//Starts a new or restarts an existing Loader in this manager
Log.i(TAG, " onResume");
getLoaderManager().restartLoader(0, null, this);
}
private void displayListView() {
Log.i(TAG, " Starting displayListView");
// The desired columns to be bound
String[] columns = new String[] {
TDAdb.COL_CHAPTER,
TDAdb.COL_CHAPTERTITLE};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.chapter1,
R.id.chaptertitle1,
};
// create an adapter from the SimpleCursorAdapter
dataAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.chapter_info,
null,
columns,
to,
0);
// get reference to the ListView
ListView listView = (ListView) getView().findViewById(R.id.chapterlist);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//Ensures a loader is initialized and active.
getLoaderManager().initLoader(0, null, this);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String chaptervalueselected =
cursor.getString(cursor.getColumnIndexOrThrow(TDAdb.COL_CHAPTER));
mCallback.onChapterSelected(chaptervalueselected, position);
Toast.makeText(getActivity(), "Chapter " + chaptervalueselected, Toast.LENGTH_SHORT).show();
// starts a new Intent to update/delete a Chapter
// pass in row Id to create the Content URI for a single row
//Intent chapterEdit = new Intent(getBaseContext(), ChapterEdit.class);
//Bundle bundle = new Bundle();
//bundle.putString("mode", "update");
//bundle.putString("rowId", rowId);
//chapterEdit.putExtras(bundle);
//startActivity(chapterEdit);
}
});
}
// This is called when a new Loader needs to be created.
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.i(TAG, " onCreateLoader");
String[] projection = {
TDAdb.KEY_ROWID,
TDAdb.COL_CHAPTER,
TDAdb.COL_CHAPTERTITLE};
CursorLoader cursorLoader = new CursorLoader(getActivity(),
TDAProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.i(TAG, " ononLoadFinished");
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
dataAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
Log.i(TAG, " onLoaderReset");
dataAdapter.swapCursor(null);
}
}
If you are already using the add method of FragmentTransaction you must not include the <fragment tag in your layout. What if you just left your main activity XML like this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
In chapterFragment.java change your import
import android.app.Fragment
To
import android.support.v4.app.Fragment

How to display an existing ListFragment in a DialogFragment

I have the following problem:
I have an exisiting ListFragment, but I would like to display this as a dialog.
My first approach was to create a DialogFragment which has to ListFragment inside of it, but appearently it is currently not possible to put fragments in fragments.
Extending DialogFragment instead of ListFragment is also not possible, because of the heavy use of ListFragment methods.
Is there an easy way to do this?
What works for me is
1) in xml layout for your DialogFragment called, let's say, DialogFragmentwWithListFragment specify ListFragment class
E.g. dialog_fragment_with_list_fragment.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding = "10dp"
class="com.xxx.yyy.DialogFragmentwWithListFragment " />
</LinearLayout>
2) in DialogFragmentwWithListFragment inflate dialog_fragment_with_list_fragment.xml
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dialog_fragment_with_list_fragment, null);
}
3) invoke DialogFragmentwWithListFragment as regular DialogFragment:
DialogFragmentwWithListFragment dialogFragment = DialogFragmentwWithListFragment .newInstance();
dialogFragment.setRetainInstance(true);
dialogFragment.show(getFragmentManager(), "tag");
Hope, it helps.
I would either put the ListView inside a DialogFragment or try to put the ListFragment inside a Dialog. I am not sure if the second one is possible though.
You can show a list through a DialogFragment this way:(using the support v4 library)
public class MyListDialogFragment extends DialogFragment {
onDlgListClick mCallback;
private String[] lista;//the list you want to show with the dialog
public static MyListDialogFragment newInstance(Bundle fB){
MyListDialogFragment lstFrag = new MyListDialogFragment();
Bundle args = new Bundle();
args.putStringArray("lista", fB.getStringArray("lista"));//the list
args.putString("titulo", fB.getString("titulo"));//the title of the list
lstFrag.setArguments(args);
return lstFrag;
}
public interface onDlgListClick{
public void onLstItemSelected(String selection);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (onDlgListClick) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement onLstItemSelected");
}
this.setCancelable(false);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
lista = getArguments().getStringArray("lista");
return new AlertDialog.Builder(getActivity())
.setTitle(getArguments().getString("titulo"))
.setCancelable(false)
.setItems(lista, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int item){
mCallback.onLstItemSelected(lista[item]);
getDialog().dismiss(); //maybe you dont need these two lines
MyListDialogFragment.this.dismiss();
}
}).create();
}
}
On the main activity you extend FragmentActivity and implements the interface MyListDialogFragment.onDlgListClick
//the interface
#Override
public void onLstItemSelected(String selection) {//list dialog fragment interface
//do whatever you want
}
//calling the dialog
public void showFrags(int id){
Bundle fB = new Bundle();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("listdialog");
if (prev != null) {
ft.remove(prev);
}
ft.commit();
switch(id){
case 0:
fB.putStringArray("lista", list); fB.putString("titulo",title);
MyListDialogFragment newListDlg = MyListDialogFragment.newInstance(fB);
newListDlg.show(ft, "listdialog");
break;
}
}
When adding a fragment inside another fragment, the documentation says you should do it dynamically (i.e., rather than hardcoding a <fragment> tag into your layout XML.
So here is how to do it dynamically. In this case, I add MyListFragment to MyDialogFragment:
MyDialogFragment.java
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MyDialogFragment extends DialogFragment {
public static final String TAG = MyDialogFragment.class.getSimpleName();
private static final String ARG_TITLE = "ARG_TITLE";
private EditText mEditText;
public MyDialogFragment() {
// Empty constructor required for DialogFragment
}
public static MyDialogFragment newInstance(String title) {
MyDialogFragment myDialogFragment = new MyDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
myDialogFragment.setArguments(args);
return myDialogFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
dialog.setTitle(args.getString(ARG_TITLE));
}
return dialog;
}
public void setTitle(String title) {
Dialog dialog = getDialog();
dialog.setTitle(title);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_fragment_selected_products, container, false);
//addInnerFragment();
Button okButton = (Button)view.findViewById(R.id.okButton);
okButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
//dismissAllowingStateLoss();
}
}
);
return view;
}
#Override
public void onStart() {
super.onStart();
//addInnerFragment();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
addInnerFragment();
}
public void addInnerFragment() {
FragmentManager childFragmentManager = getChildFragmentManager();
FragmentTransaction transaction = childFragmentManager.beginTransaction();
//transaction.add(R.id.fragmentContainer, new MyListFragment());
transaction.add(R.id.fragmentContainer, MyListFragment.newInstance(MyListFragment.MODE_SELL));
//transaction.commit();
transaction.commitAllowingStateLoss();
childFragmentManager.executePendingTransactions();
}
}
(As you will see, it also contains some functionality to set the title of the dialog.)
dialog_fragment_selected_products.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MyDialogFragment"
android:orientation="vertical">
<LinearLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_above="#+id/okButton" />
<Button
android:id="#+id/okButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/ok" />
</RelativeLayout>
Another advantage of doing it this way is that you can create an instance of the inner fragment in order to pass any arguments to it.
For completeness, here is the code that I use in my activity to show the DialogFragment:
MyActivity.java
private void showCurrentItemsDialog() {
MyDialogFragment myDialogFragment = MyDialogFragment.newInstance("cpuk.org");
//myDialogFragment.setRetainInstance(true);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(myDialogFragment, MyDialogFragment.TAG);
transaction.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();
}

Categories

Resources