我试图在点击按钮并在TextView上设置其值后选择日期。 这个主题帮助Datepicker: How to popup datepicker when click on button and store value in variable
但是我无法在setText上设置datepicker的值,textview对象v返回空nullpointerexception。
v.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("/").append(mDay).append("/")
.append(mYear).append(" "));
System.out.println(v.getText().toString());
感谢任何帮助
完整代码: Mainactivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void pick(View v){
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
System.out.println("the selected " + mDay);
DatePickerDialog dialog = new DatePickerDialog(MainActivity.this,
new mDateSetListener(), mYear, mMonth, mDay);
dialog.show();
}
}
class mDateSetListener implements DatePickerDialog.OnDateSetListener {
private TextView v;
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
// getCalender();
int mYear = year;
int mMonth = monthOfYear;
int mDay = dayOfMonth;
v.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("/").append(mDay).append("/")
.append(mYear).append(" "));
}
}
xml文件:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.datesamp.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="101dp"
android:text="Pick date"
android:onClick="pick"/>
<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
/>
</RelativeLayout>
答案 0 :(得分:0)
在onDateSet()中使用变量之前,需要初始化变量 v ,例如:在 v .setText(...)之前添加以下语句:
v = (TextView) findViewById(R.id.t1);
v.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("/").append(mDay).append("/")
.append(mYear).append(" "));
但是为了在onDateSet()中插入这个语句,我建议你将类 mDateSetListener 定义为 MainActivity 中的内部类,它会让你的生活更轻松