我有一个警告对话框,我使用自定义布局为此警报对话框,在这个自定义布局我有一个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()
}
}
像widget
之前那样在你的自定义Dialog
中初始化findViewById
:
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