每当我在Android应用程序中进行while循环时,它会导致我的屏幕仅显示基本背景&行动吧。当我在我的应用程序中发现这一点时非常令人沮丧,我花了几个小时试图寻找解决方法。我做了一个非常基本的程序,试图缩小原因并发现它是while循环,这让我留下了一个黑屏。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign Variables
EditText editText_HEX = (EditText)findViewById(R.id.EditText_HEX);
String stringHEX = editText_HEX.getText().toString();
Boolean isHex = stringHEX.matches("^#([A-Fa-f0-9]{6})$");
// I have (true) in right now, but if I change that to a more specific boolean I still
// can't see the page of my app.
while (true){
// Here I'm trying to get the loop to pause until the user enters 7 characters
// into the EditText box.
// I've tried while (editText_HEX.length() < 7) as well, but still get a blank page
while (stringHEX.length() < 7){
}
Toast.makeText(getApplicationContext(), "text reached 7 characters", Toast.LENGTH_SHORT).show();
break;
}
}
我没有在logcat中收到任何错误 - 应用程序工作正常,它只是没有显示我的任何小部件。如果我删除while循环,它就可以工作。
我最终想要得到的东西: 我正在尝试创建一个应用程序,要求用户输入一个可更改背景颜色的十六进制值。在我之前的问题(已经回答)中,我想出了如何检查有效的十六进制。现在我希望这个循环运行,以便一个人可以在EditText框中输入十六进制颜色,背景颜色将立即改变;如果他们在文本框中重新输入不同的十六进制,背景将再次改变。这个while循环只是一个简单的程序,我用它来缩小我的页面空白的原因。
我一直在不同项目中处理应用的不同部分。这是一个 - 然后我在计算出这些错误的原因之后,计划制作更大的最终应用程序。我是Android的编程新手,所以如果有一个简单的解决方法,我会很感激帮助。谢谢!
答案 0 :(得分:3)
不要使用循环试试这个:
editText_HEX.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// check for valid hex here
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
答案 1 :(得分:0)
默认情况下,stringHEX中文本的长度为0.而在onCreate本身甚至在显示布局之前,你有一个while循环,它检查stringHEX的长度。由于它变成了无限循环,你在屏幕上没有任何东西。只是为了测试,在你的xml中为你的stringHEX提供一个虚拟文本,它应该可以正常工作。