Kotlin:在NavigationDrawerActivity的Fragment中实现Button点击切换文本
嘿,我来帮你搞定这个问题!你需要在FirstFragment里完成控件的初始化和点击事件绑定,具体修改如下:
核心修改思路
我们需要在Fragment视图创建完成后,获取TextView和Button的实例,然后给Button添加点击监听器,通过一个布尔变量来切换文本内容。
修改后的FirstFragment代码
class FirstFragment : Fragment() { private var mParam1: String? = null private var mParam2: String? = null private var mListener: OnFragmentInteractionListener? = null // 用来记录当前文本状态 private var isHi = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { mParam1 = arguments.getString(ARG_PARAM1) mParam2 = arguments.getString(ARG_PARAM2) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater!!.inflate(R.layout.fragment_first, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 获取TextView和Button实例 val textView = view.findViewById<TextView>(R.id.text) val toggleButton = view.findViewById<Button>(R.id.button) // 设置点击事件 toggleButton.setOnClickListener { // 切换状态 isHi = !isHi // 根据状态设置文本 textView.text = if (isHi) "Hi" else "Hello" } } fun onButtonPressed(uri: Uri) { if (mListener != null) { mListener!!.onFragmentInteraction(uri) } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnFragmentInteractionListener) { mListener = context } else { throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } interface OnFragmentInteractionListener { fun onFragmentInteraction(uri: Uri) } companion object { private val ARG_PARAM1 = "param1" private val ARG_PARAM2 = "param2" fun newInstance(param1: String, param2: String): FirstFragment { val fragment = FirstFragment() val args = Bundle() args.putString(ARG_PARAM1, param1) args.putString(ARG_PARAM2, param2) fragment.arguments = args return fragment } } }
关键修改点说明
- 添加状态变量:
private var isHi = false用来记录当前显示的是"Hi"还是"Hello",每次点击按钮就取反这个变量。 - 在
onViewCreated中初始化控件:这个方法是在Fragment的视图完全创建完成后调用的,在这里获取控件实例不会出现空指针问题。 - 绑定点击事件:给Button设置
setOnClickListener,每次点击时切换isHi的状态,并更新TextView的文本。
这样修改后,你点击FirstFragment里的按钮,TextView的文本就会在"Hi"和"Hello"之间来回切换啦~
内容的提问来源于stack exchange,提问作者a2krocks
相关产品推荐
相关产品推荐

