[android]使用 Activity 中的方法Fragment

发布时间: 2016/9/26 3:54:05
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

你好,我是一个业余 Android ,和我有巨大的问题,用 activity 方法在我 fragment 类。

我想要执行 setContentViewfindViewByIdgetMenuInflater 。不幸的是,我不知道如何去做。

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

    }

}

解决方法 1:

fragment中"contentView"(在你的 meanign) 定义在 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();
官方微信
官方QQ群
31647020