如何以编程方式创建具有id和src参数的imageView?

时间:2012-12-15 00:59:01

标签: android android-layout android-imageview android-framelayout

以下工作,但我想消除xml,以便我可以编程方式更改图像: 爪哇:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.p6_touch);
    ImageView floatImage = (ImageView) findViewById(R.id.p6_imageView);
    floatImage.setOnTouchListener(this);    
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/background_black" >
    <ImageView
        android:id="@+id/p6_imageView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="matrix"
        android:src="@drawable/p6_trail_map" >
    </ImageView>
    <ImageView
          android:id="@+id/imageView1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="bottom"
          android:onClick="showFlashlight"
          android:src="@drawable/legend_block24" />
</FrameLayout>

1 个答案:

答案 0 :(得分:8)

在文档中有一个table,它将XML映射到Java。

  • 例如:android:src相当于setImageResource()

您需要检查inherited table中任何超类的属性。

  • 例如:android:id相当于setId()

widthheightgravity都在LayoutParams对象中设置并传递给setLayoutParams()

了解并非每个XML属性都具有匹配的Java方法(反之亦然),但您使用的所有属性都是如此。


示例,让我们调用此文件activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/background_black" >
    <!-- We'll add this missing ImageView back in with Java -->
    <ImageView
          android:id="@+id/imageView1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="bottom"
          android:onClick="showFlashlight"
          android:src="@drawable/legend_block24" />
</FrameLayout>

现在我们的活动:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Let's create the missing ImageView
    ImageView image = new ImageView(this);

    // Now the layout parameters, these are a little tricky at first
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT);

    image.setScaleType(ImageView.ScaleType.MATRIX);
    image.setImageResource(R.drawable.p6_trail_map);
    image.setOnTouchListener(this);    

    // Let's get the root layout and add our ImageView
    FrameLayout layout = (FrameLayout) findViewById(R.id.root);
    layout.addView(image, 0, params);
}