访问活动中片段内的textview

flo*_*oat 5 android communication android-fragments

我想在ActionBar中使用Fragments.不幸的是,它看起来真的很复杂.我的片段有Textviews,我希望能够通过我的活动与他们进行交流.在我开始使用Fragments之前,我可以使用它来访问它们

private EditText editText = (EditText) findViewById(R.id.editTextName);
Run Code Online (Sandbox Code Playgroud)

因此,当用户单击"保存"时,我能够收到editText值.我应该怎样做片段式的方式?

活动:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_recipe);
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    getSupportActionBar().setDisplayOptions(0, com.actionbarsherlock.app.ActionBar.DISPLAY_SHOW_HOME | com.actionbarsherlock.app.ActionBar.DISPLAY_USE_LOGO | com.actionbarsherlock.app.ActionBar.DISPLAY_SHOW_TITLE);

    ActionBar.Tab newTab0 = getSupportActionBar()
            .newTab()
            .setText(R.string.fragment_general)
            .setTabListener(
            new MyTabListener<GeneralFragment>(this, "general",
                            GeneralFragment.class));


    getSupportActionBar().addTab(newTab0);

}
public static class MyTabListener<T extends Fragment> implements
        TabListener {
    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    /**
     * * Constructor used each time a new tab is created. * * @param
     * activity * The host Activity, used to instantiate the fragment * @param
     * tag * The identifier tag for the fragment * @param clz * The
     * fragment's Class, used to instantiate the fragment
     */

    public MyTabListener(Activity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (mFragment == null) {
            // If not, instantiate and add it to the activity
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            // If it exists, simply attach it in order to show it
            //ft.setCustomAnimations(android.R.animator.fade_in, R.animator.animationtest);
            ft.attach(mFragment);
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            //ft.setCustomAnimations(android.R.animator.fade_in, R.animator.test);
            ft.detach(mFragment);
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 12

您应该在Fragment上调用getView(),然后在返回的视图上使用findViewById().

当然,在创建视图之后它不会返回任何内容,所以你可能不得不在onCreate之外的某个地方调用它.