我无法从Activity类中获取TextView(在Fragment的xml中定义)的引用。任何人都可以请看一下我在这里缺少的东西。
我的activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
和fragment_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#FFEBCC">
<TextView android:id="@+id/dateArea" android:layout_height="wrap_content" android:layout_width="wrap_content"
android:text="@string/app_name"/>
以下活动类Toast NULL值dateArea TextVew:
public class MainActivity extends ActionBarActivity {
....
....
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
....
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
dateArea = (TextView)findViewById(R.id.dateArea);
Toast.makeText(this, dateArea.toString(),Toast.LENGTH_LONG).show(); //dateArea is NULL !!
}
}
感谢您的帮助。
答案 0 :(得分:0)
试试这个..
您的TextView
属于fragment_main.xml
,因此您必须在PlaceholderFragment
中对其进行初始化,并且您必须先将文字显示在Toast
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
TextView dateArea;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
dateArea = (TextView) rootView.findViewById(R.id.dateArea);
Toast.makeText(getActivity(), dateArea.getText().toString(),Toast.LENGTH_LONG).show();
return rootView;
}
}
答案 1 :(得分:0)
如果要引用片段的UI元素,则必须在活动中获取片段的视图实例。
fragment.getView().findViewByID(id);
由于片段和活动具有更多#34;自己&#34; findViewByID方法引用其膨胀的布局