我有一个警报对话框,并且为此警报对话框使用了自定义布局,在此自定义布局中,我有一个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()
}
}
答案 0 :(得分:1)
在widget
之前,像在自定义Dialog
中一样初始化findViewById
:
txtlyric = (TextView) dialog.findViewById(R.id.yourtextviewindialog);
然后,您将可以setText
或自己的对话框小部件中的内容。
P.s:请注意,我使用dialog
是因为它是您的Dialog
视图。
答案 1 :(得分:1)
我建议使用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