Android根据Locale获取String

在开发应用时,某些场景需要我们通过代码动态的获取string中的字符串,调用的context.getString()方法,这个方法返回的是默认的string.xml中的资源,如果用户切换了locale,那么这个方法返回的可能还是默认的语言。如何通过Locale来获取对应的string资源呢?

获取Locale

Locale locale = Locale.getDefault();

获取对应的字符资源

public static String getString(Context context
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Android设备上获取用户的当前位置并获取城市,可以使用Android系统提供的LocationManager类和Geocoder类。 首先,需要在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.INTERNET"/> ``` 然后,在代码中使用LocationManager类获取设备的当前位置: ```java LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); ``` 这里使用NETWORK_PROVIDER来获取网络位置,也可以使用GPS_PROVIDER来获取GPS位置。获取到位置后,就可以使用Geocoder类将位置转换成城市: ```java Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); String city = addresses.get(0).getLocality(); ``` 这里需要注意的是,getFromLocation方法需要在异步线程中执行,以避免阻塞UI线程。完整的代码示例如下: ```java public class MainActivity extends AppCompatActivity { private TextView cityTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cityTextView = findViewById(R.id.city_text_view); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { new GetCityTask().execute(location); } } private class GetCityTask extends AsyncTask<Location, Void, String> { @Override protected String doInBackground(Location... locations) { Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault()); List<Address> addresses = null; try { addresses = geocoder.getFromLocation(locations[0].getLatitude(), locations[0].getLongitude(), 1); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.size() > 0) { return addresses.get(0).getLocality(); } else { return null; } } @Override protected void onPostExecute(String city) { if (city != null) { cityTextView.setText(city); } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值