Kurczak222 Kurczak222 - 4 months ago 18
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

setContentView
,
findViewById
and
getMenuInflater
. Unfortunately, I don't know how to do it.

public class WagaFragment extends Fragment{

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


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**setContentView**(R.layout.activity_main);


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

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

fromSpinner.setAdapter(adapter);
toSpinner.setAdapter(adapter);

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


Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(Color.YELLOW);


}

@Override
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);
toEditText.setText(String.valueOf(result));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);

}

}

Answer

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();