在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
当前回答
有几种方法可以做到这一点:
保存活动状态
您可以在onSaveInstanceState中保存活动状态。
@Override
public void onSaveInstanceState(Bundle outState) {
/*Save your data to be restored here
Example: outState.putLong("time_state", time); , time is a long variable*/
super.onSaveInstanceState(outState);
}
然后使用捆绑包恢复状态。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!= null){
/*When rotation occurs
Example : time = savedInstanceState.getLong("time_state", 0); */
} else {
//When onCreate is called for the first time
}
}
自行处理方向更改
另一种选择是自己处理方向更改。但这并不是一种好的做法。
将此添加到清单文件中。
android:configChanges="keyboardHidden|orientation"
对于Android 3.2及更高版本:
android:configChanges="keyboardHidden|orientation|screenSize"
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Handle rotation from landscape to portrait mode here
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
//Handle rotation from portrait to landscape mode here
}
}
限制旋转
您还可以将活动限制在纵向或横向模式,以避免旋转。
将此添加到清单文件中的活动标记:
android:screenOrientation="portrait"
或者在活动中以编程方式实现:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
其他回答
在该活动集中,配置更改如下
android:configChanges="orientation|screenSize|keyboardHidden"
我刚刚发现了这个传说:
为了通过方向更改保持活动活动,并通过onConfigurationChanged处理活动,上面的文档和代码示例在Manifest文件中建议:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
这有一个额外的好处,那就是它总是有效的。
另一个好处是,省略keyboardHidden可能看起来合乎逻辑,但它会导致模拟器失败(至少对于Android 2.1):只指定方向会使模拟器有时同时调用OnCreate和onConfigurationChanged,而其他时候只调用OnCreate。
我还没有看到设备出现故障,但我听说过其他设备的仿真器出现故障。因此值得记录。
onConfigurationChanged is called when the screen rotates.
(onCreate is no longer called when the screen rotates due to manifest, see:
android:configChanges)
清单的哪个部分告诉它“不要调用onCreate()”?
而且谷歌的文档说要避免使用android:configChanges(除非作为最后手段)。但是,他们建议的替代方法都使用android:configChanges。
根据我的经验,模拟器总是在旋转时调用onCreate()。但我运行相同代码的1-2台设备……没有。(不知道为什么会有什么不同。)
尽管这不是“Android方式”,但我自己处理方向变化,并简单地在视图中重新定位小部件,以将改变的方向考虑在内,从而获得了非常好的结果。这比任何其他方法都快,因为您的视图不必保存和恢复。它还为用户提供了更无缝的体验,因为重新定位的小部件是完全相同的小部件,只是移动和/或调整大小。不仅可以以这种方式保存模型状态,还可以保存视图状态。
RelativeLayout有时对于需要不时调整自身方向的视图来说是一个不错的选择。您只需为每个子控件提供一组纵向布局参数和一组景观布局参数,每个参数上有不同的相对定位规则。然后,在onConfigurationChanged()方法中,将适当的值传递给每个子级的setLayoutParams()调用。如果任何子控件本身需要在内部重新定向,只需调用该子控件上的方法来执行重新定向。该子控件类似地调用其任何需要内部重新定向的子控件上的方法,依此类推。
经过一段时间的反复尝试,我找到了一个在大多数情况下都能满足我需求的解决方案。以下是代码:
清单配置:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pepperonas.myapplication">
<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
主要活动:
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Fragment mFragment;
private int mSelected = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate " + "");
// null check not realy needed - but just in case...
if (savedInstanceState == null) {
initUi();
// get an instance of FragmentTransaction from your Activity
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
/*IMPORTANT: Do the INITIAL(!) transaction only once!
* If we call this everytime the layout changes orientation,
* we will end with a messy, half-working UI.
* */
mFragment = FragmentOne.newInstance(mSelected = 0);
fragmentTransaction.add(R.id.frame, mFragment);
fragmentTransaction.commit();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, "onConfigurationChanged " +
(newConfig.orientation
== Configuration.ORIENTATION_LANDSCAPE
? "landscape" : "portrait"));
initUi();
Log.i(TAG, "onConfigurationChanged - last selected: " + mSelected);
makeFragmentTransaction(mSelected);
}
/**
* Called from {@link #onCreate} and {@link #onConfigurationChanged}
*/
private void initUi() {
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate instanceState == null / reinitializing..." + "");
Button btnFragmentOne = (Button) findViewById(R.id.btn_fragment_one);
Button btnFragmentTwo = (Button) findViewById(R.id.btn_fragment_two);
btnFragmentOne.setOnClickListener(this);
btnFragmentTwo.setOnClickListener(this);
}
/**
* Not invoked (just for testing)...
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState " + "YOU WON'T SEE ME!!!");
}
/**
* Not invoked (just for testing)...
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState " + "YOU WON'T SEE ME, AS WELL!!!");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume " + "");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause " + "");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy " + "");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_fragment_one:
Log.d(TAG, "onClick btn_fragment_one " + "");
makeFragmentTransaction(0);
break;
case R.id.btn_fragment_two:
Log.d(TAG, "onClick btn_fragment_two " + "");
makeFragmentTransaction(1);
break;
default:
Log.d(TAG, "onClick null - wtf?!" + "");
}
}
/**
* We replace the current Fragment with the selected one.
* Note: It's called from {@link #onConfigurationChanged} as well.
*/
private void makeFragmentTransaction(int selection) {
switch (selection) {
case 0:
mFragment = FragmentOne.newInstance(mSelected = 0);
break;
case 1:
mFragment = FragmentTwo.newInstance(mSelected = 1);
break;
}
// Create new transaction
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frame, mFragment);
/*This would add the Fragment to the backstack...
* But right now we comment it out.*/
// transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
以及样本片段:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* @author Martin Pfeffer (pepperonas)
*/
public class FragmentOne extends Fragment {
private static final String TAG = "FragmentOne";
public static Fragment newInstance(int i) {
Fragment fragment = new FragmentOne();
Bundle args = new Bundle();
args.putInt("the_id", i);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "onCreateView " + "");
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
可以在github上找到。