问题
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. 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
回答1:
The Fragment
is not a Activity
which means you can not use activity methods or it's lifecycle. This means you cant find views in the onCreate()
method of a Fragment
and you can not use findViewById
on it either.
This is the Android lifecycle https://stackoverflow.com/a/36340059/4467208
and to adjust your code according to that, move your findViews
into onCreateView()
like this
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.
来源:https://stackoverflow.com/questions/42229282/findviewbyid-with-fragments