您的位置:首页 > 移动开发 > Android开发

Android新版SDK中findViewById返回空指针问题

2015-05-26 10:24 330 查看
Android SDK改版之后,以前教学视频和书籍中所写响应控件的方法已经失效,在调用findViewById方法后返回null。

经研究发现,在layout布局中含有activity_main.xml和fragment_main.xml两个文件,如果你的控件定义在fragment_main.xml中,则按照以往的方法在OnCreate函数中调用findViewById方法无法获取控件指针,现给出解决方法如下:

定义一个TextView和一个Button,fragment_main.xml如下:

<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.jack.helloandroid.MainActivity$PlaceholderFragment" >

    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />

    <Button

        android:id="@+id/btn_test"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/textView1"

        android:layout_marginTop="80dp"

        android:layout_toRightOf="@+id/textView1"

        android:text="@string/button_name"

         />

</RelativeLayout>

MainActivity.java类中

/**

     * A placeholder fragment containing a simple view.

     */

    public static class PlaceholderFragment extends Fragment {

   

    private TextView myTextView = null;

        public PlaceholderFragment() {

        }

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container,

                Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_main, container, false);

            

            myTextView = (TextView)rootView.findViewById(R.id.textView1);

       

        Button btn = (Button)rootView.findViewById(R.id.btn_test);

        btn.setOnClickListener(MyClickListener);

            

            return rootView;

        }

        

        private OnClickListener MyClickListener = new OnClickListener()

        {

        public void onClick(View v)

            {

                 String message = "You click the button";

                myTextView.setText(message);

            }

        };

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android