android - TextView 返回 null

标签 android nullpointerexception textview

我有一个监听器,它只更改按钮的文本并为用户计时。我还有一个 TextView ,它应该在用户下类时更改为新的总工作时间。我仔细检查了 xml 以确保我获取了正确的 R.Id,并且发现了监听器中的按钮而不是 TextView。这是代码:

public class HoursListener implements OnClickListener{

GlobalApp appState;
Button startStopHoursButton;
TextView hoursTotalTextView;
public boolean clockedIn;

public HoursListener(Context ctx){
    appState = ((GlobalApp)ctx.getApplicationContext());
}

public void onClick(View v) {
    startStopHoursButton = (Button) v.findViewById(R.id.hourstogglebutton);
    hoursTotalTextView = (TextView) v.findViewById(R.id.totalWorktimeTextView);
    if(!clockedIn){
        startStopHoursButton.setText(R.string.clockout);
        appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().CreateFinishTimeStamp();
        clockedIn = true;
    }else{
        startStopHoursButton.setText(R.string.clockin);
        appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().CreateFinishTimeStamp();
        clockedIn = false;
        hoursTotalTextView.setText(appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().totalTimeDoneThisWeekToString());                
    }
}

这是 textView 的 xml:

<TextView
        android:id="@+id/totalWorktimeTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"/>

错误在于这一行:

hoursTotalTextView.setText(appState.getCurrentCompany().getCurrentNewWeeklyTimestamp().totalTimeDoneThisWeekToString());

我正在考虑将代码放在 Activity 本身中,但我觉得我可以这样做。我想要一些我可以像听众一样调用的东西,所以我减少了代码中的冗余。我已经仔细检查过它是 null 的 hoursTotalTextView。然而按钮不是。有什么想法吗?

显示相关值不为空的 Eclipse 屏幕截图(链接到全尺寸版本): Screenshot of Eclipse

最佳答案

想必你正在监听点击的onClickListener是按钮吧? onClick 传递被单击的 View v - 即按钮 - 并且文本框不是按钮的子项,因此您找不到它。

如果在您的 Activity 中声明了 HoursListener,只需执行 findViewById 而不是 v.findViewById 即

hoursTotalTextView = (TextView) findViewById(R.id.totalWorktimeTextView);

如果没有,将 textview 传递给 HoursListener 构造函数并在那里设置 hoursTotalTextView(请记住,这感觉可能会导致内存泄漏)。

关于android - TextView 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10163694/

相关文章:

android - 如何使 TextView 中特定单词的出现可点击

java - 我不知道如何修复这个 NullPointerException

java - 我只想解析 json,其中部分是 2 两个。但响应所有 json 文件解析

java - 如何使用 selenium、cucumber 和 gradle 修复 'java.lang.NullPointerException'?

java - 改造API数据在Fragment中传递

java - 切换屏幕时 LibGDX NullPointerException

android - 仅按其等宽字母的宽度将 Textview 居中

java - 奇怪的异常 : Cannot cast String to Boolean when using getBoolean

android - 如何从 AutoCompleteTextView 获取字符串文本?

java - 如何将两种不同的字体应用到TextView?