如何从另一个类为 TextView 设置文本?

我有一个警报对话框,我为此警报对话框使用了自定义布局,在这个自定义布局中,我有一个 TextView,那么如何从 MainActivity 类中为这个 TextView 设置文本?


这是我的代码:


class MainActivity : AppCompatActivity() {


        override fun onCreate(savedInstanceState: Bundle?) {

            super.onCreate(savedInstanceState)

            setContentView(R.layout.activity_main)

            var btn_ShowAlert =findViewById<Button>(R.id.Button)


            btn_ShowAlert.setOnClickListener {       


                txtlyric.text ="this Textview is all the problem xD "


                val dialog = AlertDialog.Builder(this)

                val dialogView = layoutInflater.inflate(R.layout.lyric,null)


                dialog.setView(dialogView)

                dialog.setCancelable(true)

                dialog.show()                

            }

    }


忽然笑
浏览 204回答 2
2回答

牛魔王的故事

我建议使用 DialogFragment 并将必要的值传递给构造函数public class MyAlertDialogFragment extends DialogFragment {&nbsp; &nbsp; public static final String TITLE = "dataKey";&nbsp; &nbsp; public static MyAlertDialogFragment newInstance(String dataToShow) {&nbsp; &nbsp; &nbsp; &nbsp; MyAlertDialogFragment frag = new MyAlertDialogFragment();&nbsp; &nbsp; &nbsp; &nbsp; Bundle args = new Bundle();&nbsp; &nbsp; &nbsp; &nbsp; args.putString(TITLE, dataToShow);&nbsp; &nbsp; &nbsp; &nbsp; frag.setArguments(args);&nbsp; &nbsp; &nbsp; &nbsp; return frag;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public Dialog onCreateDialog(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; String mDataRecieved = getArguments().getString(TITLE,"defaultTitle");&nbsp; &nbsp; &nbsp; &nbsp; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());&nbsp; &nbsp; &nbsp; &nbsp; LayoutInflater inflater = getActivity().getLayoutInflater();&nbsp; &nbsp; &nbsp; &nbsp; View view = inflater.inflate(R.layout.alert_layout, null);&nbsp; &nbsp; &nbsp; &nbsp; TextView mTextView = (TextView) view.findViewById(R.id.textview);&nbsp; &nbsp; &nbsp; &nbsp; mTextView.setText(mDataRecieved);&nbsp; &nbsp; &nbsp; &nbsp; setCancelable(false);&nbsp; &nbsp; &nbsp; &nbsp; builder.setView(view);&nbsp; &nbsp; &nbsp; &nbsp; Dialog dialog = builder.create();&nbsp; &nbsp; &nbsp; &nbsp; dialog.getWindow().setBackgroundDrawable(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new ColorDrawable(Color.TRANSPARENT));&nbsp; &nbsp; &nbsp; &nbsp; return dialog;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java