如何在java类中引用布局

时间:2015-02-23 00:40:55

标签: java android xml layout

例如在java类的onCreate方法中,为了在你输入的布局中找到元素

        txtViewRed = (TextView) findViewById(R.id.txtViewRed);

我想以编程方式更改布局的背景颜色。如何参考布局以进行更改?

即。

myLayout = .....?

3 个答案:

答案 0 :(得分:0)

您可以在setBackgroundColor收到的实例中使用findViewById方法。

txtViewRed.setBackgroundColor(Color.RED);

答案 1 :(得分:0)

假设这是您的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"
android:id="@+id/myRelLayout"
tools:context=".MainActivity">

<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

我已将相对布局命名为myRelLayout

然后我可以通过使用以下代码

从使用此布局的Activity中引用它
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RelativeLayout layout = (RelativeLayout) findViewById(R.id.myRelLayout);

}

然后您可以使用以下代码更改背景颜色

layout.setBackgroundColor(Color.BLUE);

答案 2 :(得分:0)

你可以在你的java类中使用setBackgroundColor()。这个方法用于布局,textview,imageview等背景。

YourLayout.setBackgroundColor(Color.Red);