用另一个片段替换一个片段时重叠

时间:2014-02-11 15:56:56

标签: java android fragment

如果用户点击其中一个列表项,我一直在尝试用另一个片段替换该片段。现在的问题是其他片段正在显示,但它没有替换前一帧,但它只是显示在前一个片段的顶部。这就是我在列表项目上调用我的新片段的方法:

            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            String sender = ((TextView) view.findViewById(R.id.sender)).getText() .toString();
            String subject = ((TextView) view.findViewById(R.id.subject)).getText() .toString();
            String fname = ((TextView) view.findViewById(R.id.file_name)).getText() .toString();


            Fragment frag =new  DisplayFragment();
            Bundle bundle = new Bundle();
            bundle.putString("file_name", fname);
             frag.setArguments(bundle);

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.fragment_frame, frag);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

与此片段相关的活动是:

 <FrameLayout
    android:id="@+id/fragment_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
/>

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</ListView>

现在新片段的代码是:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 
{
    View rootView = inflater.inflate(R.layout.activity_displayfile, container, false);
    return rootView;

}
public void onActivityCreated(Bundle savedInstanceState) 
{
    super.onActivityCreated(savedInstanceState);
    TextView tv=(TextView)getView().findViewById(R.id.textView1);
    Bundle bundle = this.getArguments();
    String myfile = (String)bundle.get("file_name");        
    tv.setText(myfile);
}

及其相关活动是:

<FrameLayout
    android:id="@+id/display_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
>
<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</FrameLayout>

所需的输出应该是新片段中的textview应该替换以前片段的全部内容。但点击我得到的项目后的输出是: enter image description here 这个“hi”应该单独显示而不是列表。看来我的代码是正确的。提前谢谢。

1 个答案:

答案 0 :(得分:-1)

这里的问题是你在一个视图中有一个框架布局和一个列表视图。您正在用片段替换帧,但列表视图仍在那里。

  1. 在xml而不是框架布局和列表视图中使用片段
  2. 创建列表片段
  3. 在活动中创建活动添加列表片段到视图
  4. 在列表项上,单击用您的片段替换列表片段。
  5. 希望这有帮助。