Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

android - findViewById returns null in fragment

I have problem using the findViewByID methond in a fragment.

The spinner in Spinner spinner = (Spinner) view.findViewById(R.id.tabsearchspinner_location); is always null. Please see the code below.

public class FragmentTabSearch extends SherlockFragment implements OnItemSelectedListener {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.fragment_tab_suggestions, container, false);

    Spinner spinner = (Spinner) view.findViewById(R.id.tabsearchspinner_location);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getSherlockActivity(), R.array.spinner_location, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    return view;
}

@Override
public void onItemSelected(IcsAdapterView<?> parent, View view,
        int position, long id) {
    // TODO Auto-generated method stub

}

@Override
public void onNothingSelected(IcsAdapterView<?> parent) {
    // TODO Auto-generated method stub

}

}

The layout file is as below (ps: I have already declared the id/tabsearchspinner_location in the values/ids.xml file): <item type="id" name="tabsearchspinner_location"></item>

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

<Spinner
    android:id="@id/tabsearchspinner_location"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ListView
    android:id="@id/tablistview_search"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

Any help is appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inflate your View without a ViewGroup, as it's simply inside your FragmentActivity:

View view = inflater.inflate(R.layout.fragment_tab_suggestions, null);

And the way IDs are added inside the XML layout files is like this:

android:id="@+id/tabsearchspinner_location"

As you can see, you're missing the +


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...