Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble with Android 's findViewById

Tags:

android

I'm using some pre-generated android code and it isn't working.

Here is the onCreateView function for a Fragment:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tabmain, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }

Here is the xml for this fragment:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.startandselect.agora.tabmain$PlaceholderFragment">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

But when I run the problem I get an error on the textView.setText line because textView is null. textView is null because the line before it failed to find the text view. The findViewById failed to find it but I do not know why.

I debugged and found that the real textView has an id: 2131492994 and the R.id.section_label has an id of 2131492997.

like image 699
Tsangares Avatar asked Feb 08 '23 04:02

Tsangares


1 Answers

Try to use the following:

TextView textView = (TextView) findViewById(R.id.section_label);

instead of:

TextView textView = (TextView) rootView.findViewById(R.id.section_label);
like image 113
Berat Cevik Avatar answered Feb 11 '23 15:02

Berat Cevik