今天编写了一个小程序,运行的时候总是出现如下的错误
找了好久,问了eoeAndroid群里的高手们才知道,我把setContentView(R.layout.main)放到了,后面,应该将其放到onCreate最前面,如下
package org.loulijun.test;
import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.LinearLayout;
public class HelloActivity extends Activity{ /** Called when the activity is first created. */ private Button blue; private Button yellow; LinearLayout linearLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); linearLayout=(LinearLayout)this.findViewById(R.id.linearLayout); blue=(Button)findViewById(R.id.blueButton); yellow=(Button)findViewById(R.id.yellowButton); blue.setOnClickListener(new ButtonListener()); yellow.setOnClickListener(new ButtonListener()); }
class ButtonListener implements OnClickListener {
@Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.blueButton: linearLayout.setBackgroundColor(Color.BLUE); break; case R.id.yellowButton: linearLayout.setBackgroundColor(Color.YELLOW); break; } } }
}
----------------------------------------
另外就是要为LinearLayout设置一个Id,然后通过ID来找到这个布局文件,后面的事件里才能够通过
linearLayout.setBackgroundColor(Color.BLUE);设置背景颜色
main.xml文件如下
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/linearLayout" > <Button android:id="@+id/blueButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/blue" /> <Button android:id="@+id/yellowButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/yellow" /></LinearLayout>
运行结果是