我有两个xml布局。
一个带按钮。
main.xml中
testOnCreate
一个只有id的相对布局。
maintwo.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.seluhadu.colorpicker.MainActivity">
<Button
android:id="@+id/button"
android:elevation="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="136dp"
tools:layout_editor_absoluteY="1dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="123dp"/>
</RelativeLayout>
我有一个MainActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.seluhadu.colorpicker.MainActivity">
</RelativeLayout>
我想单击main.xml中的Button并更改Maintwo.xml布局的背景颜色
我试着调用protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
但它在另一个xml中,所以它不起作用,因为setContentView是main.xml
如何将其他xml的id调用到我的主Activity?
如何为Button创建onClick侦听器并获取maintwo.xml的id以更改背景?
答案 0 :(得分:1)
Assuming you have two Activities, you'll need to set the button click to call startActivity to your second Activity, meanwhile passing the color data through the intent, preferably as an hexadecimal string such as #ff00ff00
for green.
How do I pass data between Activities in Android application?
时显示相邻的div之后,您可以将findViewById用于第二个布局并设置其颜色
另请参阅Color.parseColor()
答案 1 :(得分:0)
使用此
View inflatedView = getLayoutInflater().inflate(R.layout.other_layout, null);
RelativeLayout rl = (RelativeLayout) inflatedView.findViewById(R.id.your_view_id);
rl.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
有关充气布局的更多信息,请访问here。