androidandroid-fragmentstextviewlayout-inflaterandroid-inflate

Change value of TextView from fragment function


I have a fragment called SpeedometerFragment which has a respective XML layout fragment_speedometer

I have then created an independent layout called fragment_distance. There is no activity associated with this XML file.

I want to change the value of a textview "distanceText" in the fragment_distance XML file from a function call in SpeedometerFragment.

The fragment_distance is passed to a frameLayout inside my main activity.

I have tried the following inside onCreateView of SpeedometerFragment but there is no change to the textview:

speedometerFragment


       LayoutInflater inflater1 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater1.inflate(R.layout.fragment_distance, container, false);
        TextView dis = (TextView) v.findViewById(R.id.distanceText);
        dis.setText("Test");

Solution

  • I figured out a solution. I was complicating it in my original question, so there is no need to inflate anything and there is no need for the seperate fragment_distance XML file

    I created a public static TextView distance in my main activity.

    Then in my fragment, when the value of distance changes, I use Eye_Tracking_Main.distance.setText(new DecimalFormat("#.#").format(distance) + " Km"); to set the value of the TextView

    In my main activity , I simply used distance=findViewById(R.id.distancemain);