我有一个简单的类,可以动态地将一个片段添加到活动
public class mainfilm extends FragmentActivity
{
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(android.R.id.content, new showdesc());
ft.commit();
//EditText et=(EditText)findViewById(R.id.editText1);
//et.setText("hello world");
}
}
片段代码如下:
public class showdesc extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.showdesc,container,false);
}
}
片段showdesc的xml是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:inputType="textMultiLine"
android:hint="stoyr comes here"
android:gravity="top|left"
android:background="#1919a1">
<requestFocus />
</EditText>
</LinearLayout>
对于静态添加的片段,我可以使用R.id.editText1并访问edittext。如何在活动中访问editText以获取动态添加的片段。 感谢
编辑:
我已经克服了这个: 如果你在onCreate()中添加片段,你可以在活动的onResume()方法中访问它的UI组件,而不是在那之前,因为那时片段的onResume()已被调用并且功能完全正常。
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "onresume of activity", Toast.LENGTH_SHORT).show();
EditText et=(EditText)findViewById(R.id.editText1);
et.setText("hello world dfasdfasf");
}
通过这种方式,您可以访问活动中片段的UI。
希望这会有所帮助
答案 0 :(得分:1)
改变这个:
return inflater.inflate(R.layout.showdesc,container,false);
到此:
View RootView = inflater.inflate(R.layout.showdesc,container,false);
return RootView;
然后找到你的editText:
EditText et=(EditText) RootView.findViewById(R.id.editText1);