Reputation: 35
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()
}
}
Upvotes: 1
Views: 196
Reputation: 6989
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
Upvotes: 1
Reputation: 16976
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.
P.s: Note that i used dialog
since it's your Dialog
view.
Upvotes: 1