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;
}
}
Related
I'm trying to place multiple graphs in a Fragment. So I have some FrameLayout container in a LinearLayout, in the main fragment.
When I make the transaction of all my GraphWidgetFragment in their container, the result I get is the last GraphWidgetFragment instance is in the container intented for first graph.
Also, all other containers are filled with default GraphWidgetFragment, but it seems that those ones don't even pass through onCreateView/onResume etc because I'm updating the TextView in it and the text displayed is the original one (set in xml).
I know all my graph instances are existing somewhere because I can access them and get values put at construction, but except the last one, others are not visible.
I replaced GraphFragment with a simple BlankFragment to make it easier to understand and debug.
I put onClickListener on FrameLayout containers, so I know that each container is at the right place.
I tryed to move transaction to onViewCreated() but same result. I tryed to do commit()/commitNow()/commitNowAllowingStateLoss() between all transaction, executePendingTransaction(), setReorderingAllowed(), still the same result as sending all in one commit.
Fragments are not replaced/superposed in same container, I tried using add() instead of replace() and set transparent colors.
Here is the "main Fragment" code : (onCreateView()
public class FMGraphsFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5);
if (savedInstanceState == null) {
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.setReorderingAllowed(true);
transaction.add(R.id.temp_graph_container, new BlankFragment(0), EXTTEMP.toString());
transaction.add(R.id.ltft_graph_container, new BlankFragment(1), LTFT.toString());
transaction.add(R.id.stft_graph_container, new BlankFragment(2), STFT.toString());
transaction.add(R.id.lambda_graph_container, new BlankFragment(3), LAMBDA.toString());
transaction.add(R.id.realtemp_graph_container, new BlankFragment(4), REALTEMP.toString());
transaction.add(R.id.dutycycle_graph_container, new BlankFragment(5), DUTYCYCLE.toString());
transaction.commit();
} else {
for(Integer a : list) {
Fragment fragment = getChildFragmentManager().findFragmentByTag(LAMBDA.toString());
if (fragment instanceof BlankFragment) {
((BlankFragment)fragment).setA(a);
}
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.view_fragment_graphs, container, false);
}
}
And my futur GraphWidgetFragment (aka Blank) :
public class BlankFragment extends Fragment {
private int a;
public BlankFragment() {
// Required empty public constructor
a = 999;
}
public BlankFragment(int b) {
a = b;
}
public static BlankFragment newInstance(String param1, String param2) {
return new BlankFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView tv = (TextView) getActivity().findViewById(R.id.texttt);
String s = "";
for (int i = 0; i < a; i++) {
s = s + " ";
}
s = s + String.valueOf(a);
tv.setText(s);
}
public void setA(int a) {
this.a = a;
}
public int getA() {
return a;
}
}
The main fragment xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/margin_fine"
tools:context=".ui.graph.FMGraphsFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/temp_graph_container"
android:layout_width="match_parent"
android:layout_height="#dimen/graph_height"
android:layout_margin="#dimen/margin_fine">
</FrameLayout >
<FrameLayout
android:id="#+id/ltft_graph_container"
android:layout_width="match_parent"
android:layout_height="#dimen/graph_height"
android:layout_margin="#dimen/margin_fine">
</FrameLayout>
<FrameLayout
android:id="#+id/stft_graph_container"
android:layout_width="match_parent"
android:layout_height="#dimen/graph_height"
android:layout_margin="#dimen/margin_fine">
</FrameLayout>
<FrameLayout
android:id="#+id/lambda_graph_container"
android:layout_width="match_parent"
android:layout_height="#dimen/graph_height"
android:layout_margin="#dimen/margin_fine">
</FrameLayout>
<FrameLayout
android:id="#+id/realtemp_graph_container"
android:layout_width="match_parent"
android:layout_height="#dimen/graph_height"
android:layout_margin="#dimen/margin_fine">
</FrameLayout>
<FrameLayout
android:id="#+id/dutycycle_graph_container"
android:layout_width="match_parent"
android:layout_height="#dimen/graph_height"
android:layout_margin="#dimen/margin_fine">
</FrameLayout>
<FrameLayout
android:id="#+id/dummy"
android:layout_width="match_parent"
android:layout_height="50dp">
</FrameLayout>
</LinearLayout>
</ScrollView>
Here is what I get:
Phone screenshot
I don't know where to search next so... I rely on you
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
I have created tabbed activity with two tab (edittext in tab1,listview in tab2),and I pass data in tab1 to listview in tab2, how to set title for listview
please help
my 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: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="store.exercise.com.store.MainActivity$PlaceholderFragment">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
fragment one:
public class FragmentOne extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_one, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
fragment two :
public class FragmentTwo extends Fragment {
ListView listView;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
}
protected void displayReceivedData(String message) {
arrayList.add(message);
adapter.notifyDataSetChanged();
}
}
my ViewPagerAdapter :
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new FragmentOne();
} else if (position == 1) {
fragment = new FragmentTwo();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = " مهمة جديدة ";
} else if (position == 1) {
title = " المهام ";
}
return title;
}
}
make sure you have the following on your activity_view.xml where you have your viewpager
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/center_section_tab_bar_header_height"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
and in your activity class add the following line to setup the viewpager with the tab layout header
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(yourviewpager);
after which it sets up the header for your tabs as mentioned in your code
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");
}
}
I'm trying to change a Textview's text inside a fragment, but it gaves me a NullPointerException at the setName method.
I have already tried 2 ways to do this:
public class MemberFragment extends Fragment {
private TextView tvName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
return view;
}
public void setName(String name) {
tvName.setText(name);
}
or:
public class MemberFragment extends Fragment {
private static TextView tvName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_member,container, false);
return view;
}
public void setName(String name) {
tvName = (TextView) getView().findViewById(R.id.tvProfileName);
tvName.setText(name);
}
but none gave me success. Here is where I instantiate the fragment:
MemberFragment fragment = new MemberFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
fragment.setName(map.get(Tags.NAME));
and the fragment_member.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/ActionBar.Transparent.MyStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="446dp" >
<TextView
android:id="#+id/tvProfileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</ScrollView>
Can someone help me?
Thanks.
view in your onCreateView method is the rootView of your fragment.
So just add the following code in your onCreateView method to change the text of your TextView:
((TextView)view.findViewById(R.id.tvProfileName)).setText("Your new text");
try this:
tvName = (TextView) view.findViewById(R.id.tvProfileName);
instead of :
tvName = (TextView) getView().findViewById(R.id.tvProfileName);