2017-07-02 34 views
-3

我知道這是一個常見問題,但我無法找到解決方案以及我是編程初學者的事實。空點異常 - 從片段傳遞值(TexView)到MainActivity

我試圖讓text wrap around image工作,但我得到null point exception錯誤

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 

傳遞TextView的id來MainActiviy

所以我有這個Fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context="make.appaplication.Fragment4"> 



<!-- TODO: Update blank fragment layout --> 

<ImageView 
    android:layout_width="150dp" 
    android:layout_height="150dp" 
    android:src="@drawable/nature" 
    android:id="@+id/imageView" 
    android:layout_weight="1" 
    android:layout_marginRight="17dp" 
    android:layout_marginEnd="17dp" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentEnd="true" /> 

<TextView 
    android:id="@+id/textView3" 
    android:textSize="17dp" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/text_page_1" 
    android:layout_below="@+id/textView5" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentStart="true" 
    /> 

,並通過自己的價值觀到MainActivity像這樣

String text = getString(R.string.text_page_1); 

    Drawable dIcon = ContextCompat.getDrawable(getApplicationContext(),R.drawable.nature); 

    int leftMargin = dIcon.getIntrinsicWidth() + 10; 

    SpannableString ss = new SpannableString(text); 

    ss.setSpan(new MyLeadingMarginSpan2(3, leftMargin), 0, ss.length(), 0); 

    TextView messageView = (TextView) findViewById(R.id.textView3); 
    messageView.setText(ss); 

而且我的這兩行代碼

TextView messageView = (TextView) findViewById(R.id.textView3); 
    messageView.setText(ss); 

setContentView(R.layout.activity_main); 

和onCreate方法

任何人可以幫助我解決這個問題,好嗎?

回答

0

如果TextView是你Fragment裏面,那麼你就需要找到自己的FragmentView層次裏面的TextView。這通常發生內部onCreateView(),這是一個生命週期回調,只有內部存在Fragment S:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    final View rootView = inflater.inflate(R.layout.Fragment, container, false); 
    final TextView messageView = (TextView) rootView.findViewById(R.id.textView3); 
    messageView.setText("Some Text"); 
    return rootView;  
} 
+0

非常感謝您的幫助。你是唯一回答我的人。想知道爲什麼人們不喜歡這類帖子?無論如何通過'find'你的意思是在我的'Fragment4.java'裏面寫入你添加到onCreateView中的這些行嗎?那裏的實際'rootView'是什麼意思?你能指導我一步一步解決這個問題嗎? – anomaR

+0

@anomaR我想這是因爲'NullPointerException'帖子是非常普遍的,並且在幾乎所有情況下,通過搜索SO很容易找到解決方案。然而,在這種情況下,解決方案比平時複雜一點,這就是我回答的原因。 爲'Fragment'擴展根佈局的過程與'Activity'的過程不同 - 而不是使用'setContentView()',您在'onCreateView()'內部擴充佈局並返回充氣的'View '在那個方法結束時。 – PPartisan

+0

有沒有辦法幫助我通過郵件解決這個問題?我感到困惑,而不是在這裏問多個問題,也許我可以使用郵件更快地排序。 – anomaR

相關問題