刚开始编写 android 应用程序并不断收到空指针异常,我不知道为什么。我对此进行了一些研究,似乎大多数人都因为 setContentView 而得到了这个,但似乎其他人都说我的 setContentView 在正确的空间等......
int randInt;
int[] randColor = {Color.RED,Color.BLUE,Color.GREEN,Color.YELLOW,Color.BLACK,
Color.CYAN,Color.MAGENTA,Color.LTGRAY,Color.DKGRAY,Color.WHITE};
TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
View layout = findViewById(R.layout.activity_main);
layout.setOnTouchListener(this);
textView1 = (TextView) findViewById(R.id.textView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
setBackGroundColor(randInt);
}
@Override
public boolean onTouch(View v, MotionEvent e){
float xPos = e.getX();
float yPos = e.getY();
changeText(xPos,yPos);
return true;
}
public void setBackGroundColor(int randInt){
getWindow().setBackgroundDrawable(new ColorDrawable(randColor[getRandomInt()]));
}
public int getRandomInt(){
Random randomInt = new Random();
randInt = randomInt.nextInt(10);
return randInt;
}
public void changeText(float xPos, float yPos){
textView1.setText("You are at " + xPos + " , " + yPos);
}
}
<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"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp"
android:text="@string/button" />