零点异常 - 将值(TexView)从Fragment传递给MainActivity

时间:2017-07-02 10:54:49

标签: java android nullpointerexception

我知道这是一个常见问题,但我找不到解决方案,加上我是编程初学者的事实。

我正在尝试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方法

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

如果TextView位于Fragment内,那么您需要在TextView Fragment内找到View层次结构。这通常发生在onCreateView()内,这是一个仅存在于Fragment内的生命周期回调:

@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;    
}