Eduardo
Eduardo

Reputation: 7141

Fragments in Android- Cant dynamically edit text view

I get an error when I try and use: TextView tv = (TextView) getView().findViewById(R.id.textView1); inside my FragmentOne class.

I'm new to fragments and im hoping to learn PagerView but i cant work out how to dynamically change my widgets.

MainActivity.java

public class MainActivity extends FragmentActivity {
    FragmentOne mFrag;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(savedInstanceState==null){
            mFrag = new FragmentOne();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.fragment_layout, mFrag).commit();
        }

    }
}

layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:id="@+id/fragment_layout">

   <FrameLayout 
    android:id="@+id/fragment_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


</LinearLayout>

FragmentOne.java

public class FragmentOne extends Fragment {
    TextView tv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment, container, false);
        // Inflate the layout for this fragment
        tv = (TextView) getView().findViewById(R.id.textView1);
        tv.setText("Yellow World!");
        return v;
    }
}

layout/fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Blellow World!" />

</LinearLayout>

Log File: https://www.dropbox.com/home/Projects?select=log.txt The error is "Unable to start activity" The error goes away if i remove the

tv = (TextView) getView().findViewById(R.id.textView1);
            tv.setText("Yellow World!");

lines from the FragmentOne class.

I've only learnt fragments today so im sorry if its something simple!

Upvotes: 1

Views: 4064

Answers (1)

Pavlos
Pavlos

Reputation: 2181

You should use the inflated view instead of getView().

 tv = (TextView) v.findViewById(R.id.textView1);

Upvotes: 2

Related Questions