如何引用 java class 中的布局
How to refer to a layout in java class
例如在javaclass的onCreate方法中,为了在布局中找到你键入的元素
txtViewRed = (TextView) findViewById(R.id.txtViewRed);
我想以编程方式更改布局的背景颜色。如何参考布局进行修改?
即
myLayout = .....?
您可以在通过 findViewById
收到的实例中使用 setBackgroundColor
方法。
txtViewRed.setBackgroundColor(Color.RED);
假设这是您的 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);
您可以在 java class.this 方法中使用 setBackgroundColor() 用于布局、文本视图、图像视图等背景。
YourLayout.setBackgroundColor(Color.Red);
例如在javaclass的onCreate方法中,为了在布局中找到你键入的元素
txtViewRed = (TextView) findViewById(R.id.txtViewRed);
我想以编程方式更改布局的背景颜色。如何参考布局进行修改?
即
myLayout = .....?
您可以在通过 findViewById
收到的实例中使用 setBackgroundColor
方法。
txtViewRed.setBackgroundColor(Color.RED);
假设这是您的 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);
您可以在 java class.this 方法中使用 setBackgroundColor() 用于布局、文本视图、图像视图等背景。
YourLayout.setBackgroundColor(Color.Red);