繁体   English   中英

如何在Android studio中将片段分成不同的文件?

[英]How to separate fragments to different files in android studio?

我正在尝试在android studio中开发一个Android应用程序,我一直在mainActivity类中编写越来越多的片段。 我的问题是如何将这些文件与另一个文件分开? 可能我是以错误的方式做到这一点,如果是这样,有人可以告诉我该怎么做呢?

我的代码:

public class MainActivity extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {
.
.
.
public static class PlaceholderFragment1 extends Fragment {...}
public static class PlaceholderFragment2 extends Fragment {...}
public static class PlaceholderFragment3 extends Fragment {...}
}

由于它们是静态内部类,因此AndroidStudio可以轻松地为您重构这些内容。 选择PlaceholderFragment1 (只需将文本光标放在其上)并按F6(或右键单击片段名称 - >重构 - >移动)并选择“将内部类[片段名称]移动到上一级”,如果您更改名称和包想要并击中重构。

为Fragment设置静态内部类很好(在技术上可行),但是如果你想在另一个活动中重用该片段,最好重构它。 此外,大多数人都希望尽可能减少类,如果片段的功能在逻辑上与活动分开,则几乎没有理由将其保留为内部类。

您可以毫无问题地将它们作为单独的类写在同一个包中,然后只使用它们。 否则将它们写在一个单独的包中,并将它们导入为任何其他类。

首先,您需要创建一个新类(新类文件)

注意:您将需要为每个要定义片段逻辑的片段创建这样的类。

public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.article_view, container, false);
}
//logic here
}

然后你可以在你的MainActivity中使用它,它扩展了FragmentActivity,如:

MyFragment fragment= new MyFragment();

或者如果存在

fragment= (MyFragment)getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);

您可以设置要查看的片段:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.frameLayout, fragment, FRAGMENT_TAG);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft.addToBackStack(null);
            ft.commit();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM