一、前言:我真的服了,刚开始再发布运行的时候一直报这个错误“ Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference”说空指针。我也上网查了,网上说在这个错误不是setText中值的问题,是textView初始化必须要在setText()之前。后来我反复更改发现是我findViewById的时候找控件找错了,整一个大无语事件。

二、上代码

我的页面布局xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".picker.DatePickerActivity">
    <DatePicker
        android:id="@+id/dp_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:calendarViewShown="false"
        android:datePickerMode="spinner"/>
    <Button
        android:id="@+id/btn_ok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="确定"/>
    <TextView
        android:id="@+id/tv_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

对应的Activity:DatePickerActivity

public class DatePickerActivity extends AppCompatActivity implements View.OnClickListener {

    private DatePicker dp_date;
    private TextView tv_result;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker);
        findViewById(R.id.btn_ok).setOnClickListener(this);
        tv_result = findViewById(R.id.tv_date);
        dp_date = findViewById(R.id.dp_date);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_ok:
                String desc = String.format("您选择的日期是:%d年%d月%d月",dp_date.getYear(),dp_date.getMonth()+1,dp_date.getDayOfMonth());
                tv_result.setText(desc);
                break;
        }
    }
}

注意:activity中 getMonth()他的范围是0-11,因此我们需要给他加一个1

运行效果

三、总结:写页面布局的时候还是要认真看清楚自己给控件命名的名称。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐