为什么点击按钮,TextView里面的文字没有发生变化呢?
看log,可以看到正常切换fragment。为什么文字没有改变?
这是MainActivity3的代码:
public class MainActivity3 extends Activity { private Button button; private boolean flag = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main3); /** * 设置fragment3显示在layout3中 */ getFragmentManager().beginTransaction().add(R.id.layout3, new MyFragment3()).commit(); button = (Button) findViewById(R.id.cast); /** * 设置点击事件:如果当前显示的是fragment3,则切换到fragment4; * 如果当前显示的是fragment4,则切换回fragment3 */ button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); MyFragment3 myFragment3 = new MyFragment3(); MyFragment4 myFragment4 = new MyFragment4(); if (flag) { transaction.add(R.id.layout3, myFragment4); flag = false; } else { transaction.add(R.id.layout3, myFragment3); flag = true; } transaction.commit(); } }); } }
这是MyFragment3的onCreateView方法:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i("Main", "[3]onCreateView() ---->>> fragment所包含的所有view组件创建完成"); View view = inflater.inflate(R.layout.fragment2, container, false); TextView textView = (TextView) view.findViewById(R.id.text2); textView.setText("第一个fragment"); return view; }
这是MyFragment4的onCreateView方法:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i("Main", "[4]onCreateView() ---->>> fragment所包含的所有view组件创建完成"); View view = inflater.inflate(R.layout.fragment2, container, false); TextView textView = (TextView) view.findViewById(R.id.text2); textView.setText("第二个fragment"); return view; }
这是main3.xml:
这是fragment2.xml