语言切换--国际化

最常见的就是中英文切换

补充:图片也可以做国际化->比如各国国旗(通过drawable-xxx)

效果如下:

步骤如下:

1、res右键,按照下面操作中所需语言即可

2、再将之前strings.xml复制到新建的value-en 和 value-zh

 

 strings.xm(zh)

<resources>
    <string name="app_name">Test</string>
    <string name="chinese">中文</string>
    <string name="english">英文</string>
</resources>

 strings.xm(en)

<resources>
    <string name="app_name">Test</string>
    <string name="chinese">Chinese</string>
    <string name="english">English</string>

</resources>

3、在控件中通过@string/xxx 引用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textSize="20sp"
       android:text="@string/chinese" />

   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textSize="20sp"
       android:text="@string/english"/>

 
   <Button
       android:id="@+id/switchLanguage"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@string/switch_language"/>
</LinearLayout>

4、设置好切换功能

public class MainActivity extends AppCompatActivity {

	
	@BindView(R.id.switchLanguage)
	Button SwitchLanguage;

	private String sta;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ButterKnife.bind(this);

		SwitchLanguage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//获取上次保存的语言
//				SharedPreferences sp = getSharedPreferences("fileName", MODE_PRIVATE);
//				sp.getString("laguage", "zh");
				//获取当前语言
				sta = getResources().getConfiguration().locale.getLanguage();
				shiftLanguage(sta);
			}
		});
	}

    //切换语言
	public void shiftLanguage(String sta) {
		Resources resources = getResources();// 获得res资源对象
		Configuration config = resources.getConfiguration();// 获得设置对象
		DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数:主要是分辨率,像素等。

		if (sta.equals("zh")) {
			//转换为英文
			config.locale = Locale.US; // 英文
			resources.updateConfiguration(config, dm);
			recreate();
			//		sp.putString("laguage", "zh");		//保存语言选择
		} else {
			//转换为中文
			config.locale = Locale.SIMPLIFIED_CHINESE; // 英文
			resources.updateConfiguration(config, dm);
			recreate();
			//		sp.putString("laguage", "en");		//保存语言选择
		}
	}

猜你喜欢

转载自blog.csdn.net/Mr_Leixiansheng/article/details/86495757