【问题标题】:Android fragment - findViewById returns null [duplicate]Android片段-findViewById返回null [重复]
【发布时间】:2014-09-15 19:27:54
【问题描述】:

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

@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);
        }
    }

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

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;
    }

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" />

列表视图实际上在 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="" />

有人知道缺少什么吗?

【问题讨论】:

  • Listview 属于fragment_customer.xml.post 一样
  • 干净构建你的项目。显示您的 activity_customer.xml
  • ListView lv = (ListView) findViewById(android.R.id.list);在片段 onCreateView() 上移动这条线
  • View rootView = inflater.inflate(R.layout.fragment_customer,container, false); ListView lv = (ListView) rootView.findViewById(android.R.id.list); return rootView;
  • 非常感谢。我不习惯碎片,但似乎我的问题很简单。我在使用 viewpager 时遇到了同样的问题,但您的解决方案在这种情况下不起作用。如果它一直困扰着我,我会发布另一个问题。再次感谢您!

标签: android android-fragments nullpointerexception findviewbyid


【解决方案1】:

如果您想在片段中使用列表视图,请将此行移至 onCreateView() 后使用以下内容

ListView lv = (ListView)rootview.findViewById(android.R.id.list);

【讨论】:

  • cannot resolve "rootview" symbol :(
  • @dialex rootview 不是预定义的符号。它是为将在片段中膨胀的视图赋予的名称。它可以有任何名称。
  • @dialex 你的函数->onCreateView 应该看起来像-> Bundle savedInstanceState) { View rootview=null; rootview=inflater.inflate(R.layout.fragment_web_view,容器,假); ListView lv = (ListView)rootview.findViewById(android.R.id.list);返回根视图;
猜你喜欢
  • 2021-11-23
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多