如何以编程方式将我的imageView以中心方式放在FrameLayout上?

时间:2016-03-14 22:29:53

标签: android android-framelayout android-layoutparams

我想在frameLayout的center_vertically上放置一个imageView。但是,我不能这样做。我尝试过FrameLayout.LayoutParams,但它没有.addRule()方法。

public class P023Deneme extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FrameLayout frameLayout=new FrameLayout(this);
    ImageView imageViewBackgroud=new ImageView(this);
    imageViewBackgroud.setImageResource(R.drawable.sample_6);

    ImageView imageViewLeftArrow=new ImageView(this);
    imageViewLeftArrow.setImageResource(R.drawable.slidersolok_logo);

    frameLayout.addView(imageViewBackgroud);
    frameLayout.addView(imageViewLeftArrow,50,50);
    setContentView(frameLayout);


}

}

1 个答案:

答案 0 :(得分:0)

用XML编写,而不是用代码编写,更容易

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/background_drawable"/>

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/arrow_drawable"/>
</FrameLayout>

如果你仍然想以编程方式进行,那么:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FrameLayout frameLayout=new FrameLayout(this);
    ImageView imageViewBackgroud=new ImageView(this);
    imageViewBackgroud.setImageResource(R.drawable.background);

    ImageView imageViewLeftArrow=new ImageView(this);
    imageViewLeftArrow.setImageResource(R.drawable.arrow);

    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL);
    frameLayout.addView(imageViewBackgroud);
    frameLayout.addView(imageViewLeftArrow, layoutParams);
    setContentView(frameLayout);
}