Android: allow portrait and landscape for tablets,

2019-01-02 16:37发布

I would like tablets to be able to display in portrait and landscape (sw600dp or greater), but phones to be restricted to portrait only. I can't find any way to conditionally choose an orientation. Any suggestions?

8条回答
情到深处是孤独
2楼-- · 2019-01-02 17:27

Following Ginny's answer, I think the most reliable way to do it is as follows:

As described here, put a boolean in resources sw600dp. It must have the prefix sw otherwise it won't work properly:

in res/values-sw600dp/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="isTablet">true</bool>
</resources>

in res/values/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="isTablet">false</bool>
</resources>

Then make a method to retrieve that boolean:

public class ViewUtils {
    public static boolean isTablet(Context context){
        return context.getResources().getBoolean(R.bool.isTablet);
    }
}

And a base activity to extend from the activities where you want this behaviour:

public abstract class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!ViewUtils.isTablet(this)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}

So each activity would extend BaseActivity:

public class LoginActivity extends BaseActivity //....

Important: even if you extend from BaseActivity, you must add the line android:configChanges="orientation|screenSize" to each Activity in your AndroidManifest.xml:

    <activity
        android:name=".login.LoginActivity"
        android:configChanges="orientation|screenSize">
    </activity>
查看更多
像晚风撩人
3楼-- · 2019-01-02 17:28

Well, this is a bit of late but, here is an XML-Only but a hack solution which does not recreate an activity as setRequestedOrientation does if has to change orientation:

https://stackoverflow.com/a/27015879/1281930

查看更多
登录 后发表回答