将视图从MainActivity添加到另一个XML文件布局



我想将我的主动脉中的imageView添加到另一个XML文件(layout.xml(务实地,我尝试了此代码,但它不起作用,这是代码源MainAttivity,Activity_Main.xml和Layout.xml:

主动脉:

public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
ImageView imageView;
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = new ImageView(this);
    linearLayout = (LinearLayout)findViewById(R.id.id_layout);
    imageView.setImageResource(R.drawable.ic_launcher_background);
    linearLayout.addView(imageView);
    dialog = new Dialog(this);
    dialog.setContentView(linearLayout);
    dialog.show();
}}

这是主要活动的XML文件activity_main.xml:

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="sofware.dz.test.MainActivity">

</android.support.constraint.ConstraintLayout>

这是XML文件的代码源layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/id_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</LinearLayout>

看起来您在任何地方都不会充气layout.xml

您可以替换行

linearLayout = (LinearLayout)findViewById(R.id.id_layout);

与此:

linearLayout = (LinearLayout)LayoutInflater.from((Context) this).inflate(R.layout.layout, null)

您可以将膨胀的视图作为线性布局引用,因为那是XML的根视图。如果您有其他内容作为根,则必须在末尾添加findViewById(R.id.id_layout)调用。

如果您尝试创建一个Dialog,将layout.xml中定义为内容视图中定义的布局,然后从您的活动中添加ImageView,请尝试以下内容:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = new ImageView(this);
    imageView.setImageResource(R.drawable.ic_launcher_background);
    dialog = new Dialog(this);
    dialog.setContentView(R.layout.layout); // this inflates layout.xml in the dialog
    LinearLayout layout = dialog.findViewById(R.id.id_layout); // grab root view from inflated layout
    layout.addView(imageView);
    dialog.show(); // show the dialog, which now contains the ImageView
}

这是如何工作的,分步:

  1. 设置您已经在做的活动的内容视图: setContentView(R.layout.activity_main);

  2. 创建要添加的ImageView(您也已经在执行此操作(:
    imageView = new ImageView(this); imageView.setImageResource(R.drawable.ic_launcher_background);

  3. 创建对话框,并将其内容视图设置为layout.xml布局的资源ID(夸大它(:
    dialog = new Dialog(this); dialog.setContentView(R.layout.layout); // this inflates layout.xml in the dialog

  4. 从对话框中的夸大布局获取根视图:
    LinearLayout layout = dialog.findViewById(R.id.id_layout); // grab root view layout.addView(imageView);
  5. 将您的映像视图添加到根视图:
    layout.addView(imageView);

最新更新