How to Load fragment when the app launches - java

I have created an app which basically has navigation drawer and I wish to load an fragment "home" whenever the activity launches instead of main activity.
Any idea how to do it.

You can call this method to view Fragments. In your case call this method on your onCreate()
//Fragment Changer
public void changeFragment(Fragment targetfragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_fragment, targetfragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack(null)
.commitAllowingStateLoss();
}
Example Usage
changeFragment(new YourFragment());

Basic solution can be implementing something like the below code in your onCreate method.
// get fragment manager
FragmentManager fm = getFragmentManager();
// replace
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_layout, new HomeFragment());
ft.commit();

Your Activity:
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public String getHelloMessage() {
return "Hello!";
}
}
Your View:
public class MainView extends Fragment {
// Declarations
private Button testButton;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_view, container, false);
// Getting the reference of controller from Application
MainController mainController = Application.getInstance().getMainController();
// Initializing view objects
testButton = view.findViewById(R.id.test_button);
// Setting actions
testButton.setOnClickListener(mainController.getTestAction());
return view;
}
// Reference to the view Object
public Button getTestButton() {
return testButton;
}
Your main_activity.xm lto connect the fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/containerMainView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/mainView"
android:name="com.template.views.MainView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Your main_view.xml file your final view definition
<?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">
<Button
android:id="#+id/test_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="#string/say_hello" />
</RelativeLayout>

Related

TextView in Fragment Returning Null in Android Studio

i am new to Android Studio.. i am facing null pointer exception error on my TextView inside a Fragment, please help..here is my code. this is nothing but a simple interface between two fragments. i am getting Null pointer exception error when i click on an item in ListView Fragment. for sure the TextView in DetailsFragment didn't assign or point to the source of whatever it is. please help on solving this.
public class MainActivity extends AppCompatActivity implements list_Fragment.ItemSelected {
ArrayList<String> Descriptions = new ArrayList<String>();;
TextView tvDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Descriptions.add("Description for Item 1");
Descriptions.add("Description for Item 2");
Descriptions.add("Description for Item 3");
Descriptions.add("Description for Item 4");
tvDescription = findViewById(R.id.tvDescription);
}
#Override
public void onItemSelected(int index) {
tvDescription.setText(Descriptions.get(index));
}}
list_fragment
public class list_Fragment extends ListFragment {
ArrayList<String> Data = new ArrayList<String>();
ItemSelected activity;
public interface ItemSelected{
void onItemSelected(int index);
}
public list_Fragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
activity=(ItemSelected) context;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Data.add("Item 1");
Data.add("Item 2");
Data.add("Item 3");
Data.add("Item 4");
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Data));
}
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
activity.onItemSelected(position);
}
}
and the details Fragment code, where i am getting the error i believe, is
public class DetailsFragment extends Fragment {
public DetailsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return (LinearLayout) inflater.inflate(R.layout.fragment_details, container, false);
}
}
Main XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ll_Horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/listfragmentView"
android:name="com.example.fragmentcheck.list_Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="#android:color/holo_blue_dark"
tools:layout="#layout/fragment_list_" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/detailsfragmentView"
android:name="com.example.fragmentcheck.DetailsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/purple_200"
tools:layout="#layout/fragment_details" />
</LinearLayout>
ListFragment XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/design_default_color_primary_variant"
android:orientation="vertical"
tools:context=".list_Fragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
DetailsFragment XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/design_default_color_on_secondary"
android:orientation="vertical"
tools:context=".DetailsFragment">
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</LinearLayout>
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fragmentcheck, PID: 28112
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object r*emphasized text*eference
at com.example.fragmentcheck.MainActivity.onItemSelected(MainActivity.java:34)
at com.example.fragmentcheck.list_Fragment.onListItemClick(list_Fragment.java:54)
tvDescription is in the DetailsFragment layout, you need to do any layout configuration in the code for that Class
i.e.
class DetailsFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_details, container, false)
tvDescription = view.findViewById(R.id.tvDescription);
tvDescription.setText("some text");
return view
}
}
You have tvDescription in DetailsFragment xml, while you are finding it's id in MainAcitvity. MainActivity just have FragmentContainerView , it doen't have any text view inside it.
You need to inflate the Fragment's view and call findViewById() on the View it returns.
Updated DetailsFragment
public class DetailsFragment extends Fragment {
TextView tvDescription;
public DetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_details, container, false)
tvDescription = view.findViewById(R.id.tvDescription);
tvDescription.setText("some text");
return view
}
}
Change both: androidx.fragment.app.FragmentContainerView
To: fragment
In the main_activity xml

How to refresh the data after click the item on listview for fragment

I have two fragments both AFragment and BFragment. The AFragment has a ListView. The BFragment has a Texview and a Button. The Afragment will change the fragment and putString to BFragment when the user clicked the item on ListView. The BFragment got the data from Afragment and display the date to TextView. How can I do?
The sample is like that
You can use libs https://github.com/greenrobot/EventBus . very easy!!!
EventBus in 3 steps
Define events:
public static class MessageEvent { /* Additional fields if needed */ }
Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Post events:
EventBus.getDefault().post(new MessageEvent());
You can use Interface and LocalBroadcastReceiver both for refreshing the Fragment.
Create one LocalBroadcastReceiver
LocalBroadcastManager.getInstance(context).registerReceiver(refreshFragment ,
new IntentFilter("refreshFragment"));
and its Method in BFragment
private BroadcastReceiver refreshFragment = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Do The Changes You Want To Refresh BFragment
}
};
And Than Call This LocalBroadcastReceiver in OnClick Event of the Button in AFragment.
Intent intent =new Intent("refreshFragment");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
You can do this by below approach without using external libraries:
Assume you've a MainActivity which hosts the two fragments FragmetA (which has a ListView) and FragmentB (which has the TextView)
Here's the full scenario:
Create an interface # FragmentB which will be used by MainActivity to know when a list item is selected
MainActivity will register a listener to FragmentA by overriding onAttachFramemnt() and implementing this interface
When the user selects a list item from FragmentA; FragmentB will trigger the callback back to MainActivity
MainActivity will forward the trigger to a public method in FragmentB which is used to set the text of the TextView to the current item.
Here is the code:
1. Layout
1.1 activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<fragment
android:id="#+id/fragment_b"
android:name="com.example.android.sendingdatafromfragmenta_to_fragmentb.FragmentB"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/fragment_a"
android:name="com.example.android.sendingdatafromfragmenta_to_fragmentb.FragmentA"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
1.2 fragment_a
<?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"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
1.3 fragment_b
<?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"
android:orientation="vertical">
<TextView
android:id="#+id/tvSelectedItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Item selected" />
</LinearLayout>
2. Java
2.1 MainActivity
public class MainActivity extends AppCompatActivity implements FragmentA.OnListItemClickListener {
private static final String LOG_TAG = "LOG_TAG";
private FragmentB mFragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// inflating fragment B from xml
mFragmentB = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.fragment_b);
}
#Override
public void onAttachFragment(Fragment fragment) {
Log.i(LOG_TAG, "onAttachFragment");
super.onAttachFragment(fragment);
if (fragment instanceof FragmentA) {
((FragmentA) fragment).setOnListItemClickListener(this);
}
}
#Override
public void onListItemClick(String selectedITem) {
mFragmentB.setSelectedITemText(selectedITem);
}
}
2.2 FragmentA
public class FragmentA extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
final String[] data = {"item 1", "item 2", "item 3", "item 4", "item 5"};
ListView listView = view.findViewById(R.id.listView);
ArrayAdapter adapter = new ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mOnListItemClickListener != null) {
mOnListItemClickListener.onListItemClick(data[position]);
}
}
});
return view;
}
interface OnListItemClickListener {
void onListItemClick(String selectedITem);
}
OnListItemClickListener mOnListItemClickListener;
public void setOnListItemClickListener(OnListItemClickListener listener) {
mOnListItemClickListener = listener;
}
}
2.3 FragmentB
public class FragmentB extends Fragment {
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
public void setSelectedITemText(String text) {
TextView selectedItemTextView = view.findViewById(R.id.tvSelectedItem);
selectedItemTextView.setText(text);
}
}
Results

How do I dynamically make this child Fragment's TextView visible/invisible?

I have a main Activity containing a parent Fragment, which in turn contains a child Fragment. I am trying to make a TextView in the child Fragment visible/invisible dynamically.
activity_main.xml
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the Activity"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/parent_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_parent.xml
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the parent fragment"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/child_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_child.xml
<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the child fragment"
android:id="#+id/textView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="But make this text visible dynamically!"
android:id="#+id/make_this_text_visible"
android:visibility="invisible"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String PARENT_TAG = "parent_tag";
private ParentFragment mParentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
mParentFragment = ParentFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.parent_container, mParentFragment, PARENT_TAG).commit();
}
else {
mParentFragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(PARENT_TAG);
}
}
}
ParentFragment.java
public class ParentFragment extends Fragment {
public static final String CHILD_TAG = "child_tag";
private ChildFragment mChildFragment;
private List<Integer> mList;
public static ParentFragment newInstance() {
Bundle args = new Bundle();
ParentFragment fragment = new ParentFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
mList = new ArrayList<Integer>();
if (savedInstanceState == null) {
mChildFragment = ChildFragment.newInstance();
getChildFragmentManager().beginTransaction().replace(R.id.child_container, mChildFragment, CHILD_TAG).commit();
}
else {
mChildFragment = (ChildFragment) getChildFragmentManager().findFragmentByTag(CHILD_TAG);
}
getChildFragmentManager().executePendingTransactions(); //doesn't seem to do anything!
doStuff();
return view;
}
void doStuff() {
mList.add(4); //pretend this is actually querying a database.
//for simplicity it just receives a single 4.
if (mList.size() > 0) { //the list is not empty, display the text!
mChildFragment.setTextVisible(); //error! the textivew of the child fragment is null right now
}
else {
mChildFragment.setTextInvisible(); //error! the textivew of the child fragment is null right now
}
}
}
ChildFragment.java
public class ChildFragment extends Fragment {
private TextView mTextView;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
return view;
}
public void setTextVisible() {
mTextView.setVisibility(View.VISIBLE);
}
public void setTextInvisible() {
mTextView.setVisibility(View.INVISIBLE);
}
}
How can I ensure that the child fragment is formed by the time I call doStuff() in the ParentFragment?
What I would do is keep the state of the text view visibility so it can be updated properly once the view has been created if it hasn't been already. Instead of separate methods for setTextVisible() and setTextInvisible have a single method setTextVisibile(boolean isVisible) and implement it as follows:
public class ChildFragment extends Fragment {
private TextView mTextView;
private boolean mIsTextVisible;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
setTextVisible(mIsTextVisible);
return view;
}
public void setTextVisible(boolean isVisible) {
mIsTextVisible = isVisible;
if(mTextView != null) {
mTextView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
}
}
and then in the parent fragment you can call doStuff() without worrying about the current state of the views in the ChildFragment since mIsTextVisible is properly set. If the mTextView is null at the time setTextVisible() is called the visibility will still be properly set in onCreateView().
Just take care to save and restore the mIsTextVisible flag when the fragment is recreated such as when the device is rotated.
Alternative Answer Using A Callback
Using callbacks update the ParentFragment to implement
ChildFragment.OnViewCreatedListener and its method.
public class ParentFragment extends Fragment
implements ChildFragment.OnViewCreatedListener {
#Override
public void onViewCreated() {
doStuff();
}
}
And then in ChildFragment
public class ChildFragment extends Fragment {
public interface OnViewCreatedListener {
void onViewCreated();
}
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
if(getParentFragment() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getParentFragment()).onViewCreated();
} else if (getActivity() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getActivity()).onViewCreated();
}
return view;
}
}

Fragment Add causing me an error

I am trying to figure out why I am suddenly getting an error when I try to add a fragment.
public class MainActivity extends Activity implements Communicator {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_main);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragA, new FragmentA());
//I get errors on each of the adds
ft.commit();
FragmentTransaction ft2 = getFragmentManager().beginTransaction();
ft2.add(R.id.fragB, new FragmentB());
ft2.commit();
FragmentTransaction ft3 = getFragmentManager().beginTransaction();
ft3.add(R.id.fragC, new FragmentC());
ft3.commit();
}
public void respond(String str) {
//I also get an error on the following line
((FragmentB)getFragmentManager().findFragmentById(R.id.fragB)).changeText(str);
}
}
Just using the import of FragmentTransaction, I haven't made my own class.
This is my fragment A code:
public class FragmentA extends Fragment implements OnClickListener {
Button btn;
Communicator comm;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fraga, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.btn = (Button) getActivity().findViewById(R.id.buttonA);
this.btn.setOnClickListener(this);
this.comm = (Communicator) getActivity();
}
public void onClick(View v) {
this.comm.respond("Hello from Fragment A");
}
}
xml for the activity, I am not a hundred percent sure if this will fix it but would raising the API of the project make any difference at all?
<?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="com.example.tannerlangan.week11fragtalk.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#ff83ff3e"
android:id="#+id/fragA"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:background="#ff71e7ff"
android:id="#+id/fragB"></RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="#ff6d9aff"
android:id="#+id/fragC"></RelativeLayout>
</RelativeLayout>
Your fragments probably using android.support.v4.app.Fragment instead of android.app.Fragment. The quick fix is to change the signature of your fragments to something like this:
public class FragmentA extends android.app.Fragment implements OnClickListener
This is very common with programs that mix the components from support libraries and the non-support one
Try using getSupportFragmentManager() instead of getFragmentManager(). getSupportFragmentManager() is for API<14.
In your project check whether you have imported the same Fragment class in both your FragmentA and MainActivity. You might have imported android.support.v4.app.Fragment in your fragment and in MainActivity you may have imported android.app.Fragment.
If you're minSdk is <14 use fragment, fragmentManager etc from the support library(i.e android.support.v4.app.fragment and same for the fragment manager) else just import the standard fragment class(i.e android.app.Fragment).
P.S : It would be really helpfull if you provide your Error in the question as well.

Android Fragment is not displayed

I'm quite new to Android dev and I followed the official Android's "Get started".
The fact is, my fragment is not displayed on the main activity ( it worked well few days ago but I changed some lines, I don't remember which ones ). I think it's a very basic problem as I don't use sophisticated fragments : it's basically one fragment inside an activity.
This is my activity :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mysecond.MainActivity"
tools:ignore="MergeRootFrame" />
My fragment :
<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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
And the java code for this activity (I have some other activities in the app, based on the same pattern "one fragment inside one activity" and they work well...)
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container1, new PlaceholderFragment()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Any ideas ?
Thank you :)
[edit]
so this is my new onCreate method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().replace(
R.id.container1, new PlaceholderFragment()).commit();
}
Still not working for this activity (If I add a button in activity_main.xml I'll be able to see it but the I'm not able to see the TextView in the fragment...)
No errors in logcat and yes the activity is launched (I added some Log.e in onCreate and onCreateView and I cas see them)
In your onCreate methode you don't have to check if the savedInstanceState is null but if the the content of the FrameLayout you use is null
Or you simply always replace the fragment with a new one and ommit any checking.
Instead of add, you can use replace.
You can do it like below shown code:
getSupportFragmentManager().beginTransaction().replace(
R.id.container1, new PlaceholderFragment());
For me this work. Implementa a interface FragmentActions with the init() method and use this
private void showFragment(String fragmentTag){
FragmentTransaction trasaction = getSupportFragmentManager().beginTransaction();
FragmentActions fragment = (FragmentActions) getSupportFragmentManager().findFragmentByTag(fragmentTag);
if(fragment==null ){
if(lastFragmentviewed!=null)
trasaction.hide(lastFragmentviewed);
fragment = (FragmentActions) newInstance(fragmentTag);
trasaction.add(R.id.content_frame,(Fragment) fragment,fragmentTag);
}else{
if(lastFragmentviewed!=null && !lastFragmentviewed.equals(fragment))
trasaction.hide(lastFragmentviewed);
if(getSupportFragmentManager().findFragmentByTag(fragmentTag)!=null){
fragment.init();
trasaction.show((Fragment) fragment);
}else
trasaction.add(R.id.content_frame,(Fragment) fragment,fragmentTag);
}
lastFragmentviewed=(Fragment) fragment;
trasaction.commit();
}

Categories