-1
基本上我試圖完成的是將editText視圖字符串存儲在數組中,並返回隨機選擇的數組元素的值。 editText視圖可以動態添加和刪除,所以我必須考慮到這一點。我已經檢查了我的方法,但無法找到我所遇到的問題。從存儲數組中隨機選擇editText查看內容
問題是getAnswer()。目前,這個崩潰的應用程序
的Java:
公共類MainActivity擴展AppCompatActivity { 私人的LinearLayout mEditTextContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEditTextContainer = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
setContentView(activity_main);
//Button to choose random editText contents
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getAnswer();
}
});
//Button to add editText Field
final Button add_button = (Button) findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Add_Line();
}
});
//Button to remove editText Field
final Button remove_button = (Button) findViewById(R.id.remove_button);
remove_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Remove_Line();
}
});
}
public void Add_Line() {
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setText(null);
et.setHint("Enter Answer #" + (mEditTextContainer.getChildCount()+1));
et.setGravity(Gravity.CENTER);
mEditTextContainer.addView(et);
}
public void Remove_Line() {
int count = mEditTextContainer.getChildCount();
if(count == 2)
return;
else
mEditTextContainer.removeViewAt(mEditTextContainer.getChildCount()-1);
}
public void getAnswer() {
//get number of possible answers
int count = mEditTextContainer.getChildCount();
//create array to hold answers
String[] options = new String[count--];
//create temporary view to store editText view contents
View tempView;
//Loop to collect and store editText contents
for(int i = 1; i < count-1; i++) {
tempView = mEditTextContainer.getChildAt(i);
if(tempView instanceof EditText){
String tempText = ((EditText) tempView).getText().toString();
if(tempText != null){
options[i] = tempText;
}
else
return;
}
}
int number = (int)(Math.random() * count-1);
String answer = options[number];
TextView answerBox = (TextView)findViewById(R.id.textView7);
answerBox.setText(answer);
}
}
如果你的應用程序崩潰,請包括您的問題 –
品牌新的android工作室的錯誤/ stacktrace,不知道該怎麼做。但我想出了它爲什麼會崩潰,我已經把代碼放在setContentView(activity_main)之前;在onCreate方法中。儘管如此,仍然可以使用getAnswer()方法的幫助。 – JamaicanMeCode