我尝试在三种情况下更改片段活动中的TextView,但我无法更改TextView 是否有任何解决方案可以在自己的Fragment_Activity或Main_Activity中更改Fragment的TextView?
Fragment.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!");
}
fragment.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"
/>
....
在MainActivity中调用视图的片段类:
@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);
...
}
答案 0 :(得分:0)
因为我们无法看到整个Fragment.xml文件或主要活动的xml,所以无法确定问题是什么,但似乎您可能没有在Fragment.xml中指定片段类文件所以oncreate永远不会被调用。我建议您在main_weixin
xml中添加片段属性,并删除主活动中的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" />
答案 1 :(得分:0)
要知道
getView()
的onCreate返回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");
}
}