[英]How to add an ImageView to an empty layout using java in android
對於上述問題,我也一直在stackoverflow中找出很多站點和很多主題。 但是我無法解決。 所以請幫我解決這個問題。 我正在嘗試使用JAVA將ImageView添加到具有RelativeLayout作為其父布局的空布局中。 請給我一個解決方案。 提前致謝
findViewById
獲取布局 ImageView
ImageView
添加到您的布局 例:
LinearLayout layout = (LinearLayout) findViewById(R.id.your_layout_id);
ImageView imageView = new ImageView(this);
layout.addView(imageView);
注意:我使用LinearLayout是因為您只說父布局是RelativeLayout,但是忘了提到空布局的類型。
將imageView添加到布局XML文件中而不是以空行開頭將是最簡單的。 因此,您的布局XML文件可能類似於:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".[YOURACTIVITYNAME">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>
要從Java做到這一點,您可以在Activity中的幾乎任何地方插入這樣的代碼。 例如,在onCreate
方法中,擴大布局后。
ViewGroup yourEmptyLayout = (ViewGroup) findViewById(R.id.whatever_your_layout_ID_is);
ImageView myImageView = new ImageView(this);
// Add the new ImageView to the layout
yourEmptyLayout.addView(myImageView);
// You should also give your ImageView a picture to draw.
myImageView.setImageBitmap(bm);
// or
// myImageView.setImageDrawable(drawable);
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativeLayout"
tools:context=".MainActivity"/>
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(R.mipmap.ic_launcher);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
relativeLayout.addView(imageView, params);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.