如何在android中动态更改xml背景?

如何在android中动态更改xml背景?,android,Android,我需要一个逻辑来以编程方式更改xml背景,而不是从xml文件中提供背景颜色。这里我使用了setContentView(R.layout.main);在应用程序中显示xml文件。但是我需要在java代码中更改main.xml文件的背景色。获取xml根布局的实例,并根据需要多次从代码中设置其背景色,但要在UI线程中执行所有这些操作。获取xml根布局的实例,并从用户代码中设置其背景色按照您的意愿编写任意次数的代码,但请在您的UI线程中执行所有这些操作。以下是如何做到这一点 mLayout = (Re

我需要一个逻辑来以编程方式更改xml背景,而不是从xml文件中提供背景颜色。这里我使用了setContentView(R.layout.main);在应用程序中显示xml文件。但是我需要在java代码中更改main.xml文件的背景色。

获取xml根布局的实例,并根据需要多次从代码中设置其背景色,但要在
UI线程中执行所有这些操作。

获取xml根布局的实例,并从用户代码中设置其背景色按照您的意愿编写任意次数的代码,但请在您的
UI线程中执行所有这些操作。

以下是如何做到这一点

 mLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);
 mLayout.setBackgroundColor(Color.BLUE);

这是你的父母的相对安排。

这是你如何做到的

 mLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);
 mLayout.setBackgroundColor(Color.BLUE);

这里的mLayout是您的父级RelativeLayout。

以下是一个示例,展示了如何实现它。这里,我将LinearLayout作为xml文件的根节点。在java代码中,我演示了如何设置白色背景。我想这段代码会对你有所帮助

xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
-----
-----
</LinearLayout>
LinearLayout root=(LinearLayout)findViewById(R.id.root);
root.setBackgroundColor(Color.WHITE);
也可以使用十六进制代码设置颜色,如下所示

root.setBackgroundColor(Color.parseColor("#ffffff"));
即使您也可以设置可拉伸

root.setBackgroundResource(R.drawable.bg_image);

下面是一个例子,展示了如何做到这一点。这里,我将LinearLayout作为xml文件的根节点。在java代码中,我演示了如何设置白色背景。我想这段代码会对你有所帮助

xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
-----
-----
</LinearLayout>
LinearLayout root=(LinearLayout)findViewById(R.id.root);
root.setBackgroundColor(Color.WHITE);
也可以使用十六进制代码设置颜色,如下所示

root.setBackgroundColor(Color.parseColor("#ffffff"));
即使您也可以设置可拉伸

root.setBackgroundResource(R.drawable.bg_image);
GradientDrawable sd=(GradientDrawable)this.getResources().getDrawable(R.drawable.roundbordertry); sd.setColor(Color.rgb(5,5,5));NewHeadwiew.setBackgroundDrawable(sd)

////////////////////////////////////////////////////////// roundbordertry是xml文件。 newHeadView是一个线性布局。

GradientDrawable sd=(GradientDrawable)this.getResources().getDrawable(R.drawable.roundbordertry); sd.setColor(Color.rgb(5,5,5));NewHeadwiew.setBackgroundDrawable(sd)

////////////////////////////////////////////////////////// roundbordertry是xml文件。 newHeadView是一种线性布局