如何从另一个活动设置 Activity 的内容视图

How to set the content view of a Activity from another actvity

我正在构建一个音乐播放器。每当用户单击 ImageView 时,就会出现一个对话框。该对话框将有一个开关。我想说的是,每当用户打开开关时,我想将 MainActivity.javaContentView 更改为自定义布局文件。我该怎么做。

任何建议都会被接受.. 谢谢

我会向您的对话框添加一个回调,您只需调用它来设置您的内容,例如

class MyDialog(val switchChangedCallback: (Boolean) -> Unit) : DialogFragment() ...

当您更改开关时,调用回调并在 Activity 中处理结果:

val dialog = MyDialog(switchChangedCallback = { isOn ->
                if (isOn) {
                    setContentView(R.layout.abc)
                } else {
                    setContentView(R.layout.def)
                }
            })

dialog.show(supportFragmentManager, MyDialog::class.java.name)

您可能需要检查回调是否在应用轮换后仍然存在!

你可以试试below code...

对话:

Dialog dialogue = new Dialog(MainActivity.this);
        dialogue.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialogue.setCancelable(false);
        dialogue.setContentView(R.layout.dialogue);

        Switch mySwitch = (Switch) dialogue.findViewById(R.id.MYSWITCH);
        Button btnClose = (Button) dialogue.findViewById(R.id.CLOSEBTN);


        mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    setContentView(R.layout.layout1);
                }
                else{
                    setContentView(R.layout.layout2);
                }
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogue.dismiss();
            }
        });

        dialogue.show();

dialogue.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    android:layout_height="match_parent">


    <Switch
        android:id="@+id/MYSWITCH"
        android:text="Change Layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>


    <Button
        android:id="@+id/CLOSEBTN"
        android:text="Close"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

正如您的问题所述,您需要在对话中设置一个开关,因此我们需要创建一个自定义对话布局并将其应用于对话!