Android开发:如何在Fragment运行时动态获取TextView的字符串资源键
嘿,这事儿好办!我来给你讲讲怎么在Fragment里动态拿到那个hello_world对应的字符串资源~
先回顾下你现有的代码:
- 布局里的TextView:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world"/>
- strings.xml里的资源定义:
<string name="hello_world">Hello world!</string>
在Fragment中动态获取的实现方法
Fragment里获取资源得依托上下文,这里有两种靠谱的写法,都能轻松拿到目标字符串:
方法一:用requireContext()(推荐)
这个方法能确保拿到非空的上下文,避免空指针,建议在onViewCreated或者之后的生命周期方法里用(比如onStart):
// Kotlin代码示例 override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 获取字符串 val helloWorldText = requireContext().getString(R.string.hello_world) // 比如设置给TextView(假设你用了ViewBinding) binding.myTextView.text = helloWorldText }
// Java代码示例 @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // 获取字符串 String helloWorldText = requireContext().getString(R.string.hello_world); // 设置给TextView binding.myTextView.setText(helloWorldText); }
方法二:直接调用getResources()
如果确定Fragment已经关联了上下文,也可以直接这么写:
// Kotlin val helloWorldText = resources.getString(R.string.hello_world)
// Java String helloWorldText = getResources().getString(R.string.hello_world);
小提醒
- 别在
onCreate里急着拿资源,这时候Fragment可能还没绑定好上下文,容易出问题。 - 优先用
requireContext(),比context?更安全,要是Fragment已经脱离上下文,它会抛出明确的异常,方便你排查问题。
这样就能动态获取到hello_world对应的字符串啦,之后你想怎么用都可以~
内容的提问来源于stack exchange,提问作者duke
相关产品推荐
相关产品推荐

