我试图在三种情况下更改片段活动中的文本视图,但我无法更改文本视图。
是否有任何解决方案可以在自己的Fragment_Activity或Main_Activity中更改片段的文本视图?
片段.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
TextView textView = (TextView) getView().findViewById(R.id.textView1);
textView.setText("Done!");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText("Done!");
return view;
}
@Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView tv = (TextView) getView().findViewById(R.id.textView1);
tv.setText("Done!");
}
片段.xml
...
<TextView
android:textColor="@color/myBlack"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
....
调用片段类以在主活动中查看:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_weixin);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
instance = this;
...
View view2 = mLi.inflate(R.layout.fragment_blank_fragment2, null);
views.add(view2);
...
}
要知道的事情
- 在创建片段
getView()
中返回 null,因为仍然未创建视图。 - 在片段中创建一个方法,以使用片段实例为来自活动的
TextView
设置值。
例:片段
public class Fragment1 extends Fragment {
TextView tv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
tv = (TextView) view.findViewById(R.id.textView1);
tv.setText("Done!");
return view;
}
public void setViewText(String text){
tv.setText(text);
}
}
活动
public class MyActivity extends FragmentActivity {
Fragment1 fragment1;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_fragment);
//as you are using static fragment so create fragment instance using findFragmentById(id)
fragment1 = (Fragment1) getSupportFragmentManager().findFragmentById(R.id.fragment1);
fragment1.setViewText("Message");
}
}
访问官方文档 与其他片段
通信
看不到整个 Fragment.xml 文件或您的主要活动的 xml,所以我无法确定问题出在哪里,但似乎您可能没有在 Fragment.xml 文件中指定片段类,因此永远不会调用 oncreate。我建议您在 main_weixin
xml 中添加 fragment 属性,并删除主要活动中的view2
膨胀,然后您可以简单地将其添加到您的main_weixin.xml
中:
<fragment
android:name="your_package_name.Fragment"
android:id="@+id/fragment_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />