我的问题是,是否可以在没有XML的SurfaceView中添加ImageView。如果有,怎么样?我有一个具有GamePanel功能的主类,并且要应用一个方法我需要用ImageView调用它,但我不知道它是否可行。提前谢谢你。
答案 0 :(得分:1)
您需要了解Android Framework提供的View和ViewGroup。
我正在迅速理解提出解决方案。
关于View&的崩溃课程ViewGroup
在Android UI系统的根目录中,一切都是View
。
什么是View
?
它是可以在屏幕上显示的单个窗口小部件/ UI组件。视图包括按钮,TextViews, ImageViews , SurfaceView 。它们不能包含任何子视图,即它们不能保存任何其他子视图的声明
以下XML定义 不正确 :视图无法容纳其他视图
<SurfaceView
android:id="@+id/textSurfaceView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</SurfaceView>
什么是ViewGroup
?
继承自View,旨在包含和排列多个View
,也称为子视图。各种ViewGroups
是LinearLayout,RelativeLayout,FrameLayout等。
以下XML定义是 正确 : ViewGroup可以容纳另一个视图
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
解决方案
步骤1:在包含现有SurfaceView的XML中添加ViewGroup。如前所述,ViewGroups是LinearLayout,RelativeLayout,FrameLayout等。
res / layouts / your_layout.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/baseFrame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
步骤2:在创建视图时,将ImageView添加到FrameLayout。 onCreate()
活动。
setContentView(R.layout.your_layout);
FrameLayout baseFrame = (FrameLayout) findViewById(R.id.baseFrame);
ImageView imageView = new ImageView(this);
imageView.setWidth(/*As per your need*/);
imageView.setHeight(/*As per your need*/);
imageView.setId(/*Any unique positive Number*/ R.ids.imageView1); <= Required to access this view later
/*Set the layout parameters such as layout_gravity as well.*/
baseFrame.addView(imageView);
步骤3:我知道您一定想知道ImageView Id。我正在更快地为视图分配ID。
填写以下详细信息。
<resources>
<item type="id" name="imageView1" />
</resources>
步骤4:将ImageView传递给方法
ImageView myImageView = (ImageView) findViewById(R.id.imageView1);
methodToBeCalled(myImageView);
我希望有所帮助 快乐的编码!!!