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

时间:2018-02-28 22:37:03

标签: android layout imageview

我想将我的MainActivity中的ImageView实际添加到另一个xml文件(layout.xml),我试过这段代码,但它不起作用,这里是Mainactivity的代码源,activity_main.xml和layout.xml:

主要活动:

let groupedData = _.groupBy(data, access_log => { return moment .utc(access_log.last_access_at) .local() .format("YYYY-MM-DD"); });

这里是主要活动的xml文件 activity_main.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文件的代码源 layout.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>

2 个答案:

答案 0 :(得分:1)

看起来你并没有在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)电话。

答案 1 :(得分:1)

如果您尝试使用Dialog中定义的布局创建layout.xml作为内容视图,请在活动中添加ImageView,请尝试以下操作:< / p>

@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. 将ImageView添加到根视图中:
    layout.addView(imageView);