findViewById返回null,尽管存在组件的ID

时间:2014-04-04 01:51:42

标签: java android nullpointerexception

我在xml中定义了ListView

<ListView
        android:id="@+id/optionList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:entries="@array/option_array"  
 />

在相应的课程中我打电话:

final ListView list = (ListView) findViewById(R.id.optionList);
        Log.d("LISTA", list + "");//it's null

但我在list变量上得到null。我不懂为什么。怎么纠正呢?如果我得到null,我就无法将监听器添加到该列表中。

全班代码:

package com.example.smbp1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class OptionListActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_option_list);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        createListeners();
    }

    private void createListeners() {

        final ListView list = (ListView) findViewById(R.id.optionList);
        Log.d("LISTA", list + "");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.option_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    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_option_list,
                    container, false);
            return rootView;
        }
    }


}

的活动:

<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.example.smbp1.OptionListActivity"
    tools:ignore="MergeRootFrame" />

片段:

<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.example.smbp1.OptionListActivity$PlaceholderFragment" >

    <ListView
        android:id="@+id/optionList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:entries="@array/option_array"  
 />
</RelativeLayout>

修改

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_option_list, container, false);
    final ListView list = (ListView) rootView.findViewById(R.id.optionList);
    Log.d("LISTA", list + "");
    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String element = list.getSelectedItem() + "";
            Log.d("Item", element);
        }
    });

    return rootView;
}

2 个答案:

答案 0 :(得分:1)

你没有发布非常完整的代码,但是你可能在onCreate()或onAttach()中调用了这个在onCreateView()之前发生的事情?您正在查看的视图可能仍为空。

答案 1 :(得分:1)

您的optionList位于一个片段中,因此访问它也必须在其中完成。

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_option_list,
                container, false);

        // here as an example
        final ListView list = (ListView) rootView.findViewById(R.id.optionList);
        Log.d("LISTA", list + "");

        return rootView;
    }
}