MainActivity.java
package com.ample.receive;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private TextView myTextView1;
private TextView myTextView2;
private CheckBox myCheckBox;
private Button myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCheckBox=(CheckBox)findViewById(R.id.myCheckBox);
myCheckBox.setChecked(false);
myCheckBox.setOnClickListener(this);
myButton=(Button)findViewById(R.id.myButton);
myButton.setEnabled(false);
myButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.myCheckBox:
if (myCheckBox.isChecked())
{
myButton.setEnabled(true);
myTextView2.setText("abc");
}
else
{
myButton.setEnabled(false);
myTextView1.setText(R.string.text);
myTextView2.setText(R.string.no);
}
break;
case R.id.myButton:
if (myCheckBox.isChecked())
{
myTextView1.setText(R.string.ok);
}
break;
default:break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
錯誤很明顯,是空的對象,你的TextView在setText之前,要記得findviewbyId,否則就會出現這個錯誤。
myTextView1=(TextView)findViewById(R.id.myTextView1); myTextView2=(TextView)findViewById(R.id.myTextView2);把這兩句放在onCreate裡面就可以了。