2016-01-24 49 views
-2

您好我试图创建一个片段类:空对象引用)/片段

import android.support.v4.app.Fragment; 
public class UpdatesFragment extends Fragment { 
TextView output ; 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    View view = inflater.inflate(R.layout.updates_layout, null, false); 
    output = (TextView) getView().findViewById(R.id.jsonData); 
    return view; 
    } 
} 

但是当我跑我的设备上的应用程序,该应用程序中断。

在Android工作室编辑:

方法调用 'getView()findViewById(R.id.jsonData)。' 可以产生 '显示java.lang.NullPointerException'

在设备debuger :

显示java.lang.NullPointerException:尝试调用虚拟方法 “空隙android.widget.TextView.setText(java.lang.CharSequence中) “在 空对象引用

这里是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:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context=".UpdatesFragment" 

    android:background="#24ff93"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="HackPundit Blogs" 
     android:textStyle="bold" 
     android:id="@+id/heading" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:textSize="38dp" 
     android:textColor="#230cff" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="Large Text" 
     android:textSize="15dp" 
     android:textStyle="bold" 
     android:id="@+id/jsonData" 
     android:layout_marginTop="42dp" 
     android:layout_below="@+id/heading" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:textColor="#000000" /> 


</RelativeLayout> 

回答

1

权的方式得到的看法是这样:

View view = inflater.inflate(R.layout.updates_layout, null, false); 
output = (TextView) view.findViewById(R.id.jsonData); 

你必须使用充气的视角以寻找意见而不是getView()

0

引用片段中视图的正确方法是在此方法内部;

@Override 
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 

//reference your fragments views here 
    output = (TextView) getView().findViewById(R.id.jsonData); 
}