从主活动更改片段中的setText值

时间:2015-08-20 17:16:20

标签: java android android-fragments

我一直在尝试根据用户是否点击了第一个主要活动中的按钮来更改fragmentActivity中的textViews文本。我有2个xml文件和2个.java文件,当应用程序启动时,代码暂时崩溃。 这是按钮代码

public void getNum(View view) {

        buttonCheck = 1;
        }

这是FragmentTab的代码

public class FragmentTab extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_layout, container, false);

    TextView tv = (TextView) v.findViewById(R.id.text);
    tv.setText("nothing has been input yet");

    if (FirstActivity.buttonCheck == 1){
    tv = (TextView) v.findViewById(R.id.text);
    tv.setText("value");}


    FirstActivity.buttonCheck = 0;
    return v;
}

我从logcat获取代码的第一个错误是:“java.lang.NullPointerException             在com.ezentertainment.dietabialkowa.FragmentTab.onCreateView(FragmentTab.java:23)“和第23行是tv.setText("nothing has been input yet"); 非常感谢任何帮助,我已经在这个问题上奋斗了很长一段时间..

tl; dr如何根据mainActivity的输入更改片段值?

编辑:这里是fragment_layout.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:orientation="vertical"
android:background="#eaecee">

<TextView
    android:id="@+id/textResult"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:text="value"
    android:textAppearance="?android:attr/textAppearanceMedium" />

2 个答案:

答案 0 :(得分:2)

您的textview ID是

  

机器人:ID =&#34; @ + ID / textResult&#34;

那么,这就是你获得空指针异常的原因。

此外,在进行空检查时可能是个好主意。通过ID查找视图,以防万一尚未实例化,因此它不会杀死您的应用。类似于:

TextView tv = (TextView) v.findViewById(R.id.textResult);
if (tv != null){
     tv.setText("nothing has been input yet");
} else {
    // log something if you want.
}

答案 1 :(得分:0)

How about using setArguement:

In Activity:

 Bundle bundle = new Bundle();
 bundle.putString("email", email);
 FragmentA fragment = new FragmentA();
 fragment.setArguments(bundle);
  getSupportFragmentManager().beginTransaction().add(container, fragment,     tag).addToBackStack(tag).commit();     //please input container and tag yourself

In FragmentA:

    String email;
       @Override
       public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle arguments = getArguments();
    if (arguments != null)
       email = bundle.getString("email");

    ...
}