您好我是Android的业余爱好者,我在片段类中使用活动方法时遇到了很大的问题。
我想实施setContentView
,findViewById
和getMenuInflater
。不幸的是,我不知道该怎么做。
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);
}
}
答案 0 :(得分:0)
尝试onCreateView:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_name, container, false);
fromSpinner = (Spinner) view.findViewById(R.id.spinner_from);
return view;
}
答案 1 :(得分:0)
在片段中,“contentView”(在你的手边)是在public View onCreateView
程序中定义的。
根据你的代码: 你必须使用
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
<your control> = <Control type> view.findViewById(<control id>)
对于MenuInflater,请尝试:
MenuInflater inflater = getActivity().getMenuInflater();