Mischa
Mischa

Reputation: 2139

Android how do i acces elements in a fragment?

I've got an activity that loads 2 different fragments and switches between them when needed. The problem is I cant acces any elements that are in the fragments. I need to be able to set the typeface and text in the toolbar as well as be able to set the checkboxes.

fragment 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"
android:weightSum="3">

<include
    layout="@layout/toolbar_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="15dp"
    android:id="@+id/cycle_button"
    android:button="@null"
    android:background="@drawable/cycle"
    android:layout_weight="1"
    android:layout_gravity="center_vertical" />

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="15dp"
    android:id="@+id/walk_button"
    android:button="@null"
    android:background="@drawable/walk"
    android:layout_weight="1"
    android:layout_gravity="center_vertical" />

java file:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    TextView appTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
    appTitle.setText("title");

    CheckBox cycle = (CheckBox) getView().findViewById(R.id.cycle_button);
    CheckBox walk = (CheckBox) findViewById(R.id.walk_button);
}

the findViewById doesn't work on the fragment and it just keeps returning null.

Upvotes: 0

Views: 70

Answers (3)

Robin Vinzenz
Robin Vinzenz

Reputation: 1277

You could send the desired values for your elements from your activity to the fragment when you're instantiating them.

But there are several methods you can choose to communicate between your activity and a fragment: Therefore have a look at the guide Communicating with Fragments

1.) Bundle - Activity can construct a fragment and set arguments

2.) Methods - Activity can call methods on a fragment instance

3.) Listener - Fragment can fire listener events on an activity via an interface

Especially a Fragment with Arguments would be helpful to you:

In certain cases, your fragment may want to accept certain arguments. A common pattern is to create a static newInstance method for creating a Fragment with arguments. This is because a Fragment must have only a constructor with no arguments. Instead, we want to use the setArguments method such as:

public class DemoFragment extends Fragment {
    // Creates a new fragment given an int and title
    // DemoFragment.newInstance(5, "Hello");
    public static DemoFragment newInstance(int someInt, String someTitle) {
        DemoFragment fragmentDemo = new DemoFragment();
        Bundle args = new Bundle();
        args.putInt("someInt", someInt);
        args.putString("someTitle", someTitle);
        fragmentDemo.setArguments(args);
        return fragmentDemo;
    }
}

This sets certain arguments into the Fragment for later access within > onCreate. You can access the arguments later by using:

public class DemoFragment extends Fragment {
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       // Get back arguments
       int SomeInt = getArguments().getInt("someInt", 0);   
       String someTitle = getArguments().getString("someTitle", "");    
   }
}

Now we can load a fragment dynamically in an Activity with:

// Within the activity
FragmentTransaction ft =     getSupportFragmentManager().beginTransaction();
DemoFragment fragmentDemo = DemoFragment.newInstance(5, "my title");
ft.replace(R.id.your_placeholder, fragmentDemo);
ft.commit();

This pattern makes passing arguments to fragments for initialization fairly straightforward.

After instantiating your fragment you can go ahead and retrieve your desired views from the fragment's layout during inflating and set the values included in the fragment's arguments.

public class DemoFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view =  inflater.inflate(R.layout.your_fragment_layout, container, false);
        
        // Retrieve views here via findElementById etc.. and set the attributes from the fragment's arguments

        return view;
    }
}

Upvotes: 1

Alex Shutov
Alex Shutov

Reputation: 3282

In fragment view creation is done in .onCreateView() method. You can use ViewHolder pattern- save references to all views for accessing them in a future. If you want to access activity from fragment, define interface in fragment and implement it in activity, so you can make a call like: ((MyInterface) getActivity()).changeToolbar()

For passing values into fragment use static method when you create fragement. Bear in mind, that data use pass must implement Parceleable interface

Upvotes: 0

Luca Nicoletti
Luca Nicoletti

Reputation: 2417

In Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle avedInstanceState) {
   View rootView = inflater.inflate(R.layout.yourlayout, null);
   Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
   //...[other views get here]...
   return rootView;
}

Upvotes: 0

Related Questions