无法从Fragment到达TextView

时间:2015-02-20 10:23:51

标签: java android android-fragments textview

我在片段中获得对Texview的引用时遇到了一些问题,我真的不知道为什么。

这是我的 layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tvSettings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tvLogout"
        android:layout_below="@+id/tvSettings"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="5dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

这是 Java Class

public class TabPersonnalSpace extends Fragment {

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

        TextView tvSettings = (TextView)rootView.findViewById(R.id.tvSettings);
        Log.d("Debug", tvSettings.getText().toString());

        tvSettings.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT);
            }
        });

        return rootView;
    }
}

事情是:我在片段swipe时将文本打印到logcat,单击TextView时发生

有没有人能为我提供线索?

2 个答案:

答案 0 :(得分:2)

您忘了。show()显示Toast

 Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT).show();

答案 1 :(得分:0)

像这样实现onViewCreated:

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

        //instantiate tvSettings 
        TextView tvSettings = (TextView)rootView.findViewById(R.id.tvSettings);
    }