我想从我的MainActivity将一个ImageView添加到另一个xml文件(layout.xml)实际上,我试过这个代码但它不起作用,这里是Mainactivity,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();
}}
这是主要活动Activity_main.xml的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
}
这是如何工作的,一步一步:
setContentView(R.layout.activity_main);
ImageView
(你也已经这样做了):
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
layout.addView(imageView);
layout.addView(imageView);