简体   繁体   中英

How can I settext for TextView from another class?

I have an alert Dialog and I use a custom layout for this Alert Dialog, in this custom layout I have a TextView, so how can I set text for this TextView from MainActivity class?

Here is my code :

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

Initialize the widget as in your custom Dialog like this before findViewById :

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

Then you'll be able to setText or your stuff in your custom dialog widgets.

Ps: Note that i used dialog since it's your Dialog view.

I would propose to use DialogFragment and pass necessary value into constructor

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;

    }
}

For more details please check here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM