【问题标题】:Unable to correctly swap fragments on actionbar tabs无法正确交换操作栏选项卡上的片段
【发布时间】:2012-10-09 15:18:03
【问题描述】:

已阅读有关此主题的所有问题/答案,但我无法让其中任何一个为我工作。aggghh

我有 3 个操作栏标签

tab1 调用/使用动态显示“添加”按钮的片段

当按钮被点击时,我希望它自己移除“按钮片段”,并将其替换为具有一堆 EditTexts 的片段

这按预期工作。但是,当我单击另一个选项卡时,例如调用自己的片段的 tab2,来自 tab1 的 EditTexts 片段仍然存在并覆盖 tab2 片段

我认为理解我正在尝试做的是根本错误的片段不能调用另一个片段来替换自己?或者不知何故我没有正确删除以前的片段和与backstack有关的东西..????或显示和隐藏xml?????

我对此很陌生,完全糊涂了!请帮助...提前谢谢你:)

这是我使用 TabCompat.zip 示例从 android 网站 http://developer.android.com/training/backward-compatible-ui/index.html 获取最多的代码

MainActivity.java

package com.example.android.tabcompat;
public class MainActivity extends TabCompatActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TabHelper tabHelper = getTabHelper();

CompatTab tab1Tab = tabHelper.newTab("tab1")
.setText(R.string.tab_tab1)
.setTabListener(new InstantiatingTabListener(this,"A", Tab1Fragment.class));
tabHelper.addTab(tab1Tab);

        CompatTab tab2Tab = tabHelper.newTab("tab2")
            .setText(R.string.tab_tab2)
            .setTabListener(new InstantiatingTabListener(this, "B", Tab2Fragment.class));
        tabHelper.addTab(tab2Tab);

        CompatTab tab3Tab = tabHelper.newTab("tab3")
                .setText(R.string.tab_tab3)
                .setTabListener(new InstantiatingTabListener(this,"C", Tab3Fragment.class));
        tabHelper.addTab(tab3Tab);
    }

    /**
     * Implementation of {@link CompatTabListener} to handle tab change events. This implementation
     * instantiates the specified fragment class with no arguments when its tab is selected.
     */
    public static class InstantiatingTabListener implements CompatTabListener {

        private final TabCompatActivity mActivity;
        private final Class mClass;


        /**
         * Constructor used each time a new tab is created.
         * @param activity The host Activity, used to instantiate the fragment
         * @param cls      The class representing the fragment to instantiate
         */
        public InstantiatingTabListener(TabCompatActivity activity, String tag, Class<? extends Fragment> cls) {
            mActivity = activity;
            mClass = cls;

        }

        /* The following are each of the ActionBar.TabListener Callback */
        @Override
        public void onTabSelected(CompatTab tab, FragmentTransaction ft) {
            // Check if the fragment is already initialised
            Fragment fragment = tab.getFragment();
            if (fragment == null) {
                // If not, instantiate and add it to the activity
                fragment = Fragment.instantiate(mActivity, mClass.getName());
                tab.setFragment(fragment);
                ft.add(android.R.id.tabcontent, fragment, tab.getTag());
            } 
            else {
                // If it exists, simply attach it in order to show it
                ft.attach(fragment);
            }
        }


        public void onTabUnselected(CompatTab tab, FragmentTransaction ft) {
            Fragment fragment = tab.getFragment();
            if (fragment != null) {  
            ft.detach(fragment);
            }
        }

        @Override
        public void onTabReselected(CompatTab tab, FragmentTransaction ft) {
            // User selected the already selected tab. Do nothing.

    } }
      }

Tab1Fragment.java这是加载“添加按钮”的位置

package com.example.android.tabcompat;

        public class Tab1Fragment extends Fragment{

        protected int position;
        //display the add tab1 button
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            final Button btn = new Button (getActivity());
            btn.setGravity(Gravity.TOP);
            btn.setText(R.string.btn_tab1);
            btn.setId(1);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    //when button is clicked replace the button and display the tab1 form fragment


    FragmentManager fragmentManager = getFragmentManager();
    Tab1FormFragment formFragment = new Tab1FormFragment();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.replace(android.R.id.tabcontent, formFragment);
    transaction.addToBackStack(null);
    transaction.commit();
                }

            });
            return btn;

        }
    }

Tab1FormFragment.java 这个片段显示了一个从布局文件 form.xml 获得的 edittext 视图的形式

package com.example.android.tabcompat;



   public class Tab1FormFragment extends Fragment {
    protected static final String ARG_POSITION = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
       Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      View myFragmentView = inflater.inflate(R.layout.form, container, false);

      return myFragmentView;
     }

     }

form.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/petForm"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
<ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_tab_photos" />

        <EditText
            android:id="@+id/editTextName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/field_name"
            android:inputType="text" />


        <EditText
            android:id="@+id/editTextAge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/field_age"
            android:inputType="text" />
        <EditText
            android:id="@+id/editTextBreed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/field_breed"
            android:inputType="text" />

        <Spinner
            android:id="@+id/spinnerSex"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" 
            android:entries="@array/sex_arrays"
            android:hint="@string/field_sex" />

        <Button
            android:id="@+id/savePet"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/save_record" />
    </LinearLayout>`

【问题讨论】:

  • 好的,所以已经阅读了更多内容,stackoverflow.com/questions/12114150/… 并看到我的两个片段都需要是动态的。因此已将 form.xml 替换为动态创建的表单,而不是使用 layoutparams。我仍然有重叠的问题......叹息
  • 我有一个建议。您可以使用 ViewFlipper 将按钮片段和表单片段逻辑组合在同一个片段中。 ViewFlipper 的第一个孩子将是您的按钮,当用户按下按钮时,您可以使用 ViewFlipper 的方法“setDisplayedChild”来显示您的表单片段。这样您就不必更换片段,并且仍然可以获得相同的预期效果。
  • R.id.tabcontent 住在哪里?它在 MainActivity 的布局上吗?

标签: android tabs android-fragments


【解决方案1】:

您可以尝试调用非操作栏选项卡(您所说的那个有一堆 EditText),同时为片段的该实例提供一个标记,即在您的动态按钮的 onClick 方法中,在启动 Tab1formFragment 后添加此行:

getFragmentManager().beginTransaction().replace(android.R.id.tabcontent, formFragment, "FORM_FRAG").addToBackStack(null).commit();

并通过添加对 formFragment 实例的检查来更改您的操作栏选项卡事务: if(getFragmentManager().findFragmentByTag("FORM_FRAG")!=null) getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentByTag("FORM_FRAG")).commit()

此外,您可以在 onTabSelected() 方法中使用 replace() 片段事务,而不是 attach() 和 add()。

【讨论】:

    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 2012-04-05
    • 2013-04-05
    相关资源
    最近更新 更多