Android studio 新建日程在activity_main文件中,弹出的对话框是新建的一个dialog。对话框单选四个选项,左边底部取消,右边确定。选择一个选项后,该选项会浮动显示在底部
时间: 2023-05-29 15:03:22 浏览: 145
的TextView中,并且确定按钮会变为可点击状态。点击确定按钮后,选中的选项会显示在主页面上。以下是示例代码:
1. 在activity_main.xml文件中添加一个TextView和一个Button:
```
<TextView
android:id="@+id/selected_option"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Selected Option"
android:textSize="24sp" />
<Button
android:id="@+id/new_event_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Event" />
```
2. 在MainActivity.java文件中添加以下代码:
```
public class MainActivity extends AppCompatActivity {
private TextView selectedOption;
private Button newEventButton;
private String[] options = {"Option 1", "Option 2", "Option 3", "Option 4"};
private int selectedOptionIndex = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedOption = findViewById(R.id.selected_option);
newEventButton = findViewById(R.id.new_event_button);
newEventButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Show dialog
showOptionsDialog();
}
});
}
private void showOptionsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an option");
builder.setSingleChoiceItems(options, selectedOptionIndex, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
selectedOptionIndex = i;
selectedOption.setText(options[i]);
newEventButton.setEnabled(true);
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Add selected option to main page
if (selectedOptionIndex != -1) {
// Add selected option to main page
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do nothing
}
});
builder.show();
}
}
```
3. 运行应用程序并单击“New Event”按钮,将显示一个对话框,显示四个选项。单击一个选项后,该选项将显示在底部的TextView中,并且确定按钮将变为可点击状态。单击确定按钮后,选中的选项将显示在主页面上。
阅读全文