时间选择器小部件 - “id无法解析或不是字段”

时间:2011-02-18 14:14:55

标签: android android-widget datetimepicker

我收到以下行的错误:

mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mPickTime = (Button) findViewById(R.id.pickTime);

虽然在这个阶段我只是复制粘贴教程中的东西,只是为了感受它..那么我哪里出错了?

这是整个.java文件:

package com.example.hellotimepicker;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HelloTimePicker extends Activity {
    /** Called when the activity is first created. */

    private TextView mTimeDisplay;
    private Button mPickTime;

    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // capture our View elements
        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
        mPickTime = (Button) findViewById(R.id.pickTime);

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        // display the current date
        updateDisplay();

    }

 // updates the time we display in the TextView
    private void updateDisplay() {
        mTimeDisplay.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
}

2 个答案:

答案 0 :(得分:0)

听起来你错过了从教程中复制布局(xml代码)

答案 1 :(得分:0)

只是想与原始教程版本分享我的经验,因为这可能很有用。我之前用过:

import android.R;

main无法在该行解决:

setContentView(R.layout.main);

所以我将"import android.R;"更改为:

import com.example.hellodatepicker.R; //to match with the package name

发现它运行正常。