Android 中的多个视图

Multiple views in Android

我有一张背景图片:

android:background="@drawable/bg">

和一个 TextView:

final TextView theTimer = new TextView(this);

如果我使用 setContentView,我只能将其中一个放在屏幕上。 我怎样才能将它们合二为一 activity?

创建 RelativeLayout 创建 ImageView

  RelativeLayout layout = new RelativeLayout(this);
    ImageView img = new ImageView(this);
    img.setImageResource(R.drawable.your_drawable);


    TextView tv1 = new TextView(this);
    tv1.setText("B");
    RelativeLayout.LayoutParams layoutParams =new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
    tv1.setLayoutParams(layoutParams);

    layout.addView(img);
    layout.addView(tv1);

    setContentView(layout);

做这样的事情 -

my_layout.xml file

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/ll"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" 
        android:background="@drawable/bg">
    </LinearLayout>

Activity code

setContentView(R.layout.my_layout);
final TextView theTimer = new TextView(this);
LinearLayout ll = (LinearLayout)findViewByID(R.id.ll);
ll.addView(theTimer);