无法在按钮单击时替换片段

我正在尝试学习如何在android中实现片段。 所以,我在activity_main.xml中创建了两个按钮和一个片段。 如果我点击第一个按钮,fragment_one应该膨胀,同样如果我点击第二个按钮,fragment_two应该膨胀。

但问题是它不能取代片段。 当我调试代码时,View.class中的performClick()方法返回false。

LogCat中也没有错误。

我无法弄清楚代码的问题是什么。

这是activity_main.xml

  

这是fragment_one.xml

     

这是fragment_two.xml

     

这是FragmentOne.java

 package com.example.myfragmentwithbuttonapp; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentOne extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //Inflate the layout for this fragment return inflater.inflate( R.layout.fragment_one, container, false); } } 

这是FragmentTwo.java

 package com.example.myfragmentwithbuttonapp; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentTwo extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate( R.layout.fragment_two, container, false); } } 

这是MainActivity.java

 package com.example.myfragmentwithbuttonapp; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { Fragment fr; FragmentManager fm; FragmentTransaction fragmentTransaction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1 = (Button) findViewById(R.id.button1); Button button2 = (Button) findViewById(R.id.button2); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fr = new FragmentOne(); fm = getFragmentManager(); fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.fragment_place, fr); fragmentTransaction.commit(); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fr = new FragmentTwo(); fm = getFragmentManager(); fragmentTransaction = fm.beginTransaction(); fragmentTransaction.replace(R.id.fragment_place, fr); fragmentTransaction.commit(); } }); } } 

我希望我能够解释这个问题。

任何帮助表示赞赏。

谢谢

对于fragmentTransaction.replace(),您需要为片段和片段本身指定容器。 容器是将保存片段的父视图。 简单地说是FrameLayout。

现在您将R.id.fragment_place作为容器传递,但该id引用片段而不是片段容器。

在activity_main.xml中,替换:

  

有:

  

它工作得很好。 其余的代码都没问题。