1

I have this view in my main.xml layout :

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center"
    android:gravity="center">

    <Button
        android:id="@+id/btn_sign1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:layout_gravity="center"
        />

    <Button
        android:id="@+id/btn_sign 2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2"
        android:layout_gravity="center"
     />

</LinearLayout>

<Button
    android:id="@+id/sign_3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 3"
    android:layout_gravity="center"
    />

I want to use this view when I need it, so I moved it to another xml file, inner.xml, and I call this view like this :

 LayoutInflater inflater = LayoutInflater.from(this);

                    LinearLayout linlayout1 = (LinearLayout) inflater.inflate(R.layout.inner1, null, false);

But I get this error for Button 1's onClick listener :

Unable to start activity ComponentInfo{com.example.mypc.myapp/com.example.mypc.myapp.MainActivity}: java.lang.NullPointerException:

Can you tell me how to use this view correctly when I need it? Thanks.

jason
  • 6,962
  • 36
  • 117
  • 198
  • 4
    Where are you finding the Button and setting its `OnClickListener`? – Mike M. Jan 06 '16 at 09:12
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – starkshang Jan 06 '16 at 09:21

1 Answers1

0

Try this code:

LayoutInflater inflater = LayoutInflater.from(this);
View  view = (LinearLayout) inflater.inflate(R.layout.inner1, null, false);
Button button = (Button)view.findViewById(R.id.btn_sign1);
Tim
  • 41,901
  • 18
  • 127
  • 145
daibangwen
  • 16
  • 1