findViewById在Nougat上返回null,但不是Marshmallow

时间:2017-01-21 11:21:54

标签: java android findviewbyid

在棉花糖中,一切都按预期工作。但是,在Nougat中,我收到void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference错误。即使在currentWorkoutDisplay

之后,TextView currentWorkoutDisplay = (TextView) findViewById(R.id.currentWorkoutText);仍然为空

我布局的相关部分:

<TextView
            android:id="@+id/currentWorkoutText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="TextView"
            android:textAppearance="@android:style/TextAppearance.Material.Medium"
            android:textColor="?android:attr/textColorPrimary"
            android:textSize="16sp" />

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ... irrelevant code ...

    // Get user preferences
    SharedPreferences sharedpref = PreferenceManager.getDefaultSharedPreferences(this);

    // Get the currentWorkoutDisplay TextView
    TextView currentWorkoutDisplay = (TextView) findViewById(R.id.currentWorkoutText);

    // Build the string for current workout display
    String currentWorkoutText = currentProgram + currentCycleText + " - " + "Week " +
            currentWeek + " " + "Day " + currentDay;

    // Set the current workout text
    currentWorkoutDisplay.setText(currentWorkoutText);

    ... continues ...

1 个答案:

答案 0 :(得分:0)

务必检查以确保您的布局正常&#34;正常&#34;和大型设备包含相同的名称!