2017-07-02 72 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

相关问题