Android UI控件使用常见错误
一、定义错误
public class MainActivity extends AppCompatActivity {
private TextView text = findViewById(R.id.text); // 该行代码错误
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
第二行代码直接完成了UI控件的定义和绑定初始化操作。错误提示为:java.lang.NullPointerException: Attempt to invoke virtual method ‘android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()’ on a null object reference。解决这个问题的方法是在MainActivity中定义,在onCreate()方法中绑定初始化。
public class MainActivity extends AppCompatActivity {
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
}
}
二、非UI线程操作UI控件错误
错误提示为:Only the original thread that created a view hierarchy can touch its views。
android规定除了UI线程外,其他线程都不可以对那些UI控件访问和操控。但有时在非UI线程又需要访问和控制UI控件(注意:UI线程是主线程,非UI线程是子线程)。
解决这个问题的方法如下:
- handler
- Activity.runOnUIThread(Runnable)
- View.Post(Runnable)
- View.PostDelayed(Runnabe,long)
- AsyncTask
由于篇幅有限,就不进行一一讲解了,本人比较常用的方法是第二种,将下面的代码插入到子线程中即可。
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText("hello world");
}
});
三、其它错误
有时,可能只定义了控件,但没有进行绑定初始化就进行使用,错误提示为:Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ on a null object reference。
解决这个问题的方法是使用findViewById()方法和对应的控件绑定即可。