簡體   English   中英

如何在Android中使用Java將ImageView添加到空布局

[英]How to add an ImageView to an empty layout using java in android

對於上述問題,我也一直在stackoverflow中找出很多站點和很多主題。 但是我無法解決。 所以請幫我解決這個問題。 我正在嘗試使用JAVAImageView添加到具有RelativeLayout作為其父布局的空布局中。 請給我一個解決方案。 提前致謝

  1. 為您的布局設置一個ID。
  2. 使用findViewById獲取布局
  3. 創建一個新的ImageView
  4. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM