How to add fragment into fragment - java

i want to implement my_fragment1 into tab1 fragment how can i combine the fragment into fragment.
Tab1
public class Tab1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab1, container, false);
list_fragment fm = (list_fragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.My_Container_1_ID);
}
Tab1.xml
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/button"
android:layout_toStartOf="#+id/button">
</FrameLayout>

If you want add another fragment to Tab1 fragment, you can use getChildFragmentManager() to add. In onActivityCreated of Tab1 fragment,
you can add another fragment
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getChildFragmentManager().beginTransaction()
.add(R.id.My_Container_1_ID, "your fragment here")
.commit();
}
And don't write codes after return .....

Related

RecyclerView crashes with NullPointerException in Fragment

RecyclerView works normally when used in activity but when used in fragment it gives error as below
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at restaurant.menu.fragments.MealsFragment.onCreate(MealsFragment.java:42)
fragment_meals.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.MealsFragment">
<!-- TODO: Update blank fragment layout -->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvMeals"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Items> ItemsList;
ItemsList= (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getActivity().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("Meals");
recyclerView = getActivity().findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity(),RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getActivity().getApplicationContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
}
As per the Fragment lifecycle guide, onCreate() is called before onCreateView. That means that your Fragment's view hasn't been created yet.
Instead, you want to move all of your code from onCreate() into onViewCreated() - that is the method that is called after onCreateView() and is where you can access your newly inflated views. Note that you cannot and should not be using getActivity().findViewById() - that finds views in your activity's layout, not in your fragment's layout:
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("Meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}

OnClickListner interface is not working for linearlayout in the fragment

I am creating a fragment in which I'm using a clickable linearLayout as a button
I have created all the necessary methods and implemented the OnClickListener interface to the class but when i click the layout nothing happens
Here is my LinearLayout and TextView from xml and java code.
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="50dip"
android:layout_weight="1"
android:clickable="true"
android:background="#drawable/button_layout"
android:layout_margin="1dip">
<LinearLayout
android:orientation="vertical"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="e"
android:textColor="#color/abc_primary_text_disable_only_material_dark"
android:gravity="top"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="π"
android:gravity="bottom"/>
</LinearLayout>
</LinearLayout>
The mainview TextView is
<TextView android:id="#+id/mainview"
android:layout_width="match_parent"
android:background="#color/button_material_light"
android:layout_height="60dip"
android:layout_weight="1"/>
Class code is
public class HomeFragment extends Fragment implements View.OnClickListener{
TextView mainView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainView = (TextView) getActivity().findViewById(R.id.mainview);
}
public static HomeFragment newInstance(int i){
HomeFragment homeFragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt("index", i);
homeFragment.setArguments(args);
return homeFragment;
}
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt("index"));
}
#Override
public void onClick(View view) {
mainView.setText("ghalib");
}
}
I also tried debugging the program and find out that the method is not called on clicking the Layout.
Thanks to rahul to remind me to pass the "this" Object in the setOnClickListener of the Clickable LinearLayout Which I'm using as the Button
So first I assign the id to the layout by android:id="#+id/pie"
then setting the listner in the code then the new code is
public class HomeFragment extends Fragment implements View.OnClickListener{
TextView mainView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainView = (TextView) getActivity().findViewById(R.id.mainview);
//This is the New Part
((LinearLayout)getActivity().findViewById(R.id.pie))
.setOnClickListener(this);
}
public static HomeFragment newInstance(int i){
HomeFragment homeFragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt("index", i);
homeFragment.setArguments(args);
return homeFragment;
}
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity)activity).
onSectionAttached(getArguments().getInt("index"));
}
#Override
public void onClick(View view) {
mainView.setText("ghalib");
}
}

add onclick listener to a button in a fragment's xml

I'm writing and android 4.4 project using android studio.
I'm new to the fragments idea and trying to create a simple application with a button that the click handler sends a message to the log.
this is the fragment class
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_menu, container, false);
return rootView;
}
public void addStringClickHandler(View v) {
Log.d("tag","hello");
}
}
this is the fragment layout 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.tuxin.myalcoholist.myalcoholist.myalcoholist.MainMenuActivity$PlaceholderFragment">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_drink"
android:id="#+id/add_drink"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:onClick="addStringClickHandler" />
</RelativeLayout>
as you can see i set in the XML android:onclick to addStringClickHandler
and in the fragment class i created that function, but when I execute the application
I get an error that the runtime could not find a method addStringClickHandler(view)
what am I missing?
Your android:onClick handler method has to belong to the Activity hosting your fragment. Just move addStringClickHandler() method to the activity.
If you want to have a listener method in the fragment you have to set listener in the code like this.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
rootView.findViewById(R.id.add_drink).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("tag","hello");
}
});
return rootView;
}
Try to register the onClick method when inflating the view.
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
rootView.findViewById(R.id.add_drink).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do what you need
}
});
return rootView;
Or you can set the fragment to be the on click listener
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
rootView.findViewById(R.id.add_drink).setOnClickListener(this);
return rootView;
and then make the fragment implement OnClickListener.

How to setdata for a fragment when data is recieved to present activity as intents from previous activity

Overview::
I am receiving data from another activity to my present activity as
intents and im storing it in present activity as a variable named recievedData
Now my present activity has a fragment in it.
The fragment has a textview
Q::So how can i set the textview ?
MainActivityTwo.java
public class MainActivityTwo extends FragmentActivity
{
FragmentManager objFrgMng=getSupportFragmentManager();
FragmentTransaction objFrgTrns;
FragmentTwo objFrgTwo=new FragmentTwo();
String recievedData;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_act_two_container);
Bundle extras=getIntent().getExtras();
recievedData=extras.getString("key");
Log.d("RECIEVED-DATA", recievedData);
getSupportFragmentManager().beginTransaction().add(R.id.mainActTwoContainerId,objFrgTwo, "MainActFrgTwoTag").commit();
}
}
main_act_two_container.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"
android:id="#+id/mainActTwoContainerId" >
</RelativeLayout>
fragment_two.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"
android:background="#084B8A" >
<TextView
android:id="#+id/textViewId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="161dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
FragmentTwo.java
public class FragmentTwo extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View ObjFrgOneView=inflater.inflate(R.layout.fragment_two, container, false);
return ObjFrgOneView;
}
}
note:: all im doing is dynamically
With the help of Raghunandan in one of comments i was able to resolve this from this link, i am sharing the complete solution in case it might be helpful to someone
MainActivityTwo.java
public class MainActivityTwo extends FragmentActivity
{
FragmentManager objFrgMng=getSupportFragmentManager();
FragmentTransaction objFrgTrns;
FragmentTwo objFrgTwo=new FragmentTwo();
String recievedData;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_act_two_container);
Bundle extras=getIntent().getExtras();
recievedData=extras.getString("key");
Log.d("RECIEVED-DATA", recievedData);
//sending data to second fragment in second activity
Bundle bundle = new Bundle();
bundle.putString("edttext", recievedData);
objFrgTwo.setArguments(bundle);
getSupportFragmentManager().beginTransaction().add(R.id.mainActTwoContainerId,objFrgTwo, "MainActFrgTwoTag").commit();
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment{
TextView tv;
String strtext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View ObjFrgOneView=inflater.inflate(R.layout.fragment_two, container, false);
strtext = getArguments().getString("edttext");
return ObjFrgOneView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
tv=(TextView) getActivity().findViewById(R.id.textViewId);
tv.setText(strtext);
}
}

No view found for id 0x7f070000 for fragment

I get this error when I try to load my Fragment in my ActionBar.
Caused by: java.lang.IllegalArgumentException: No view found for id
0x7f070000 for fragment HomeFragment{4100e030 #0 id=0x7f070000}
public class HomeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.home, container, false);
}
}
The below is my mainActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime_mobile_home);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab homeTab = actionBar.newTab();
homeTab.setText("Home");
homeTab.setIcon(R.drawable.home);
Fragment homeFragment = new HomeFragment();
homeTab.setTabListener(new MyTabsListener(homeFragment));
actionBar.addTab(homeTab);
}
MainActivity 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" >
</RelativeLayout>
you should input viewGroup resource ID which is ContentView in ParentActivity.
does you Parent Activity have LinearLayout or Relativelayout as ContentView.
if yes, you should choose it in inflate method's augument.

Categories