简体   繁体   English

带片段的FindViewbyID

[英]FindViewbyID with fragments

I have this problem with fragments.. I wanted to add a drawer menu in my app and than work with fragments. 我遇到了片段问题。我想在我的应用程序中添加一个抽屉菜单,而不是使用片段。 I have this code, and when i putted the fragments "findviewbyid" didnt works more. 我有这段代码,当我把片段“ findviewbyid”放不下时。 Someone can help me? 有人可以帮我吗?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_contact);



    final EditText nome        = (EditText) findViewById(R.id.nome);
    final EditText citta       = (EditText) findViewById(R.id.citta);
    final EditText numero      = (EditText) findViewById(R.id.numero);
    final EditText email       = (EditText) findViewById(R.id.email);
    final EditText oggetto     = (EditText) findViewById(R.id.oggetto);
    final EditText messaggio    = (EditText) findViewById(R.id.messaggio);



    Button email = (Button) findViewById(R.id.post_message);
    email.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String name      = nome.getText().toString();
            String citta     = citta.getText().toString();
            String numero    = numero.getText().toString();
            String email     = mail.getText().toString();
            String oggetto   = oggetto.getText().toString();
            String messaggio   = messaggio.getText().toString();
            if (TextUtils.isEmpty(nome)){
                nome.setError("Inserisci il Tuo Nome");
                nome.requestFocus();
                return;
            }

thank you and sorry for my english 谢谢你,抱歉我的英语

The Fragment is not a Activity which means you can not use activity methods or it's lifecycle. Fragment不是Activity ,这意味着您不能使用活动方法或其生命周期。 This means you cant find views in the onCreate() method of a Fragment and you can not use findViewById on it either. 这意味着您无法在FragmentonCreate()方法中找到视图,也不能在其上使用findViewById

This is the Android lifecycle https://stackoverflow.com/a/36340059/4467208 这是Android生命周期https://stackoverflow.com/a/36340059/4467208

and to adjust your code according to that, move your findViews into onCreateView() like this 并据此调整代码,将findViews移到onCreateView()如下所示

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmentLayout, container, false);
    nome = (EditText) view.findViewById(R.id.nome);
    return view;
}

And so on. 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM