小编Cha*_*ine的帖子

Android片段 - findViewById返回null

我有一个在互联网上似乎很常见的问题:我创建了一个只有一个片段的活动.这是生成的代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
            ListView lv = (ListView) findViewById(android.R.id.list);
        }
    }
Run Code Online (Sandbox Code Playgroud)

在条件之后或之内,我无法使用findViewById获取任何对象:它始终为null.以下是生成的代码的其余部分:

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_customer,
                container, false);
        return rootView;
    }
Run Code Online (Sandbox Code Playgroud)

activity_customer.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.axacs.marc.CustomerActivity"
    tools:ignore="MergeRootFrame" />
Run Code Online (Sandbox Code Playgroud)

listview实际上是在fragment_customer.xml中:

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/new_folder_button"
    android:text="" />
Run Code Online (Sandbox Code Playgroud)

有谁知道缺少什么?

android nullpointerexception android-fragments findviewbyid

8
推荐指数
1
解决办法
2万
查看次数