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

How can I settext for TextView from another class?

我有一个警报对话框,我为此警报对话框使用自定义布局,在这个自定义布局中我有一个 TextView,那么如何从 MainActivity class 为这个 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()                
            }
    }

findViewById:

之前像这样在自定义 Dialog 中初始化 widget
txtlyric = (TextView) dialog.findViewById(R.id.yourtextviewindialog);

然后您将能够 setText 或在自定义对话框小部件中使用您的东西。

P.s:请注意,我使用了 dialog,因为它是您的 Dialog 视图。

我建议使用 DialogFragment 并将必要的值传递给构造函数

public class MyAlertDialogFragment extends DialogFragment {

    public static final String TITLE = "dataKey";

    public static MyAlertDialogFragment newInstance(String dataToShow) {
        MyAlertDialogFragment frag = new MyAlertDialogFragment();
        Bundle args = new Bundle();
        args.putString(TITLE, dataToShow);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        String mDataRecieved = getArguments().getString(TITLE,"defaultTitle");

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.alert_layout, null);

        TextView mTextView = (TextView) view.findViewById(R.id.textview);
        mTextView.setText(mDataRecieved);
        setCancelable(false);

        builder.setView(view);
        Dialog dialog = builder.create();

        dialog.getWindow().setBackgroundDrawable(
                new ColorDrawable(Color.TRANSPARENT));

        return dialog;

    }
}

更多详情请查看here