正与每个活动的好做法(基于Android工作室)的片段?

问题描述:

在新的Andr​​oid工作室,每次我创建向导将创建以下结构的活动:

In the new Android Studio, every time I create an activity from the wizard it will create the following structure:

public class LoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

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

}

公告有活性,它含有一个片断占位符。这被认为是一个好的做法呢?这是因为,如果你将来想支持平板电脑或更换片段,那么你可以(这就是为什么它在机器人工作室新的默认?)。

Notice there's the activity and it contains a fragment place holder. Is this considered a good practice? is it because if you wanted in the future to support tablets or replace fragment then you could (and thats why its the new default in Android studio?).

一般来说,是的,你应该尝试使用尽可能多的片段,这样你可以有不同的布局不同大小/宽高比设备。

Generally speaking, yes, you should try to use fragments as much as possible, so that you can have different layouts for different size / aspect ratio devices.

是的,这就是为什么Android的Studio生成code这样在默认情况下。

And yes, that's why Android Studio generates code that way by default.

然而,像任何好的规则,也有例外。有时,一个活动是简单的,不会在不同的设备不同。在这种情况下,一个片段不一定能使感。

However, like any good rule, there are exceptions. Sometimes, an activity is simple, and will not differ on different devices. In that case, a fragment doesn't necessarily make sense.

总之,在默认情况下使用的片段。去只有在少数情况下一个活动的地方,使您的项目中感觉你。

In short, use fragments by default. Go with just an activity in the few cases where it makes sense you in your project.