Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findViewById returns NULL when using Fragment

I'm new to Android developing and of course on Fragments.

I want to access the controls of my fragment in main activity but 'findViewById' returns null. without fragment the code works fine.

Here's part of my code:

The fragment:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:orientation="vertical"     tools:ignore="HardcodedText" >      <EditText         android:id="@+id/txtXML"         android:layout_width="fill_parent"         android:layout_height="fill_parent"         android:ems="10"         android:scrollbars="vertical">     </EditText>  </LinearLayout> 

the onCreate of MainActivity:

    @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         super.setContentView(R.layout.main);          this.initialisePaging();          EditText txtXML = (EditText) findViewById(R.id.txtXML);} 

on this point the txtXML is null.

What's Missing in my code or what should I do?

like image 591
mammadalius Avatar asked May 06 '12 08:05

mammadalius


People also ask

Can you use findViewById in fragment?

Using getView() returns the view of the fragment, then you can call findViewById() to access any view element in the fragment view.

What does findViewById return?

findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .

What does findViewById return if it doesn't find a view object with the matching ID?

. findViewById(R. id. retry) would always return null.


1 Answers

Try like this on your fragments on onCreateView

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {      if (container == null) {         return null;     }      LinearLayout ll = (LinearLayout )inflater.inflate(R.layout.tab_frag1_layout, container, false); EditText txtXML = (EditText) ll.findViewById(R.id.txtXML);      return ll; } 
like image 104
Ufuk Doganca Avatar answered Oct 16 '22 18:10

Ufuk Doganca