这是我的 onCreate 方法。我正在尝试设置按钮以将布局背景的背景更改为不同的颜色。但是 findViewById 无法获取布局。
我通过给它另一个线性布局子来修复它,但我仍然想知道它为什么不起作用。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.button1);
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
//Below is code in question: Method is not resolved to type.
button1.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
layout.setBackgroundColor(Color.argb(100, 255, 0, 0));
}
});
}
HEre is my XML:
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="linearLayout1"
>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button" />
</LinearLayout>