Kurczak222 Kurczak222 - 1 year ago 85
Android Question

Using Activity methods in Fragment

Hi I am an amateur in Android, and I've got huge problem with using activity methods in my fragment class.

I would like to implement

. Unfortunately, I don't know how to do it.

public class WagaFragment extends Fragment{

private Spinner fromSpinner, toSpinner;
private EditText fromEditText, toEditText;

public void onCreate(Bundle savedInstanceState) {

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.units, android.R.layout.simple_spinner_item);

fromSpinner = (Spinner) **findViewById**(R.id.spinner_from);
toSpinner = (Spinner) **findViewById**(R.id.spinner_to);


fromEditText = (EditText) **findViewById**(R.id.editText_from);
toEditText = (EditText) **findViewById**(R.id.editText_to);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);


public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
**getMenuInflater()**.inflate(R.menu.menu_main, menu);
return true;

public void konwertuj(View view) {
// Get the string from the Spinners and number from the EditText
String fromString = (String) fromSpinner.getSelectedItem();
String toString = (String) toSpinner.getSelectedItem();
double input = Double.valueOf(fromEditText.getText().toString());

// Convert the strings to something in our Unit enu,
Konwerter.Jednostka fromJednostka = Konwerter.Jednostka.fromString(fromString);
Konwerter.Jednostka toJednostka = Konwerter.Jednostka.fromString(toString);

// Create a converter object and convert!
Konwerter konwerter = new Konwerter(fromJednostka, toJednostka);
double result = konwerter.convert(input);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);



Answer Source

In Fragments "contentView" (in your meanign) is defined in public View onCreateView procedure.

According to your code: you have to use

View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
<your control> = <Control type> view.findViewById(<control id>)

For MenuInflater try this:

MenuInflater inflater = getActivity().getMenuInflater();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download