更改 java 代码中的 textView 导致 crash/not 工作
Changing textView in java code causing crash/not working
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String test = "test";
TextView text = (TextView) findViewById(R.id.textView);
text.setText(test);
setContentView(R.layout.activity_main);
}
问题始于一个片段,我尝试了所有 Whosebug 解决方案都无济于事,所以我重新构建了一个版本,现在我只是想让它在 MainActivity 中工作。谁能解释一下为什么这段代码不更新 textView,以及为什么会导致崩溃。
注意:我已经尝试制作自己的 setText() 方法,我已经尝试使用来自其他更安全位置的字符串和字符数组,我已经移动了 setContentView() 前后的代码,如果它只是另一个以不同的方式编码上述^的方式,我可能已经尝试过了。几乎我尝试的每件事都会导致相同的结果。这让我相信解决方案不只是在上面的代码中,还有其他被忽视的东西,可能是一个简单的修复。谢谢!
编辑:这是我的 xml,我的新生 CS 看到 android:text="" 行时感到刺痛。
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
试试这段代码在调用 findViewById 方法之前必须先调用 setcontentView 方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String test = "test";
TextView text = (TextView) findViewById(R.id.textView);
text.setText(test);
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String test = "test";
TextView text = (TextView) findViewById(R.id.textView);
text.setText(test);
setContentView(R.layout.activity_main);
}
问题始于一个片段,我尝试了所有 Whosebug 解决方案都无济于事,所以我重新构建了一个版本,现在我只是想让它在 MainActivity 中工作。谁能解释一下为什么这段代码不更新 textView,以及为什么会导致崩溃。
注意:我已经尝试制作自己的 setText() 方法,我已经尝试使用来自其他更安全位置的字符串和字符数组,我已经移动了 setContentView() 前后的代码,如果它只是另一个以不同的方式编码上述^的方式,我可能已经尝试过了。几乎我尝试的每件事都会导致相同的结果。这让我相信解决方案不只是在上面的代码中,还有其他被忽视的东西,可能是一个简单的修复。谢谢!
编辑:这是我的 xml,我的新生 CS 看到 android:text="" 行时感到刺痛。
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
试试这段代码在调用 findViewById 方法之前必须先调用 setcontentView 方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String test = "test";
TextView text = (TextView) findViewById(R.id.textView);
text.setText(test);
}