Как установить текст для TextView из другого класса?

У меня есть диалоговое окно оповещения, и я использую собственный макет для этого диалогового окна оповещения, в этом пользовательском макете у меня есть TextView, так как я могу установить текст для этого TextView из класса MainActivity?

Вот мой код:

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()                
            }
    }

person Mohamed Khaled    schedule 01.09.2018    source источник
comment
Создайте минимально воспроизводимый пример   -  person Zoe    schedule 01.09.2018
comment
пожалуйста, опубликуйте трассировку стека, спасибо   -  person Lino    schedule 01.09.2018
comment
Покажите трассировку стека из logcat, иначе никто не сможет вам помочь   -  person EpicPandaForce    schedule 01.09.2018


Ответы (2)


Инициализируйте widget как в своем пользовательском Dialog, как это было до findViewById:

txtlyric = (TextView) dialog.findViewById(R.id.yourtextviewindialog);

Затем вы сможете setText или что-то еще в своих пользовательских диалоговых виджетах.

P.s. Обратите внимание, что я использовал dialog, так как это ваше представление Dialog.

person ʍѳђઽ૯ท    schedule 01.09.2018

Я бы предложил использовать 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;

    }
}

Подробнее см. здесь

person Gleichmut    schedule 01.09.2018