在這個程序中,我有一個TextView
它說:「輸入LineData的數量:」。 在這個下面我有一個EditText
它允許單獨的數字。 下面我有一個Button
其功能是顯示EditText的值。 要從EditText
獲得整數值,我使用了Try/Catch
塊內的變量「i」。 我知道這個變量「i」在該塊之外被銷燬。 但我想用這個變量在TableLayout
中創建TableRow
。 我試圖在Try塊內做到這一點,但我得到了錯誤。 我該如何解決這個問題?如何訪問塊外的變量?
public class Ybus_Activity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ybus);
final LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
final LinearLayout main = (LinearLayout) findViewById(R.id.android_main_layout);
TextView getData = new TextView(this);
getData.setText("Enter the number of LineData : ");
getData.setId(5);
getData.setLayoutParams(params);
main.addView(getData);
final EditText edText = new EditText(this);
edText.setId(3);
edText.setLayoutParams(params);
edText.setWidth(100);
edText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
edText.setInputType(InputType.TYPE_CLASS_NUMBER);
edText.setKeyListener(DigitsKeyListener.getInstance());
edText.setMaxLines(1);
main.addView(edText);
Button bt = new Button(this);
bt.setText("Click to enter Linedata");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
main.addView(bt);
final TextView text = new TextView(this);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String ed = edText.getText().toString();
int i = 0;
try {
i = Integer.parseInt(ed);
text.setText(i + "");
} catch (NumberFormatException ex) {
text.setText("Value at TextView is not a valid integer");
}
}
});
main.addView(text);
}
}
聲明'INT I;''之前onCreate'。 – Raghunandan
@Raghunandan:它不工作...我需要更新的值...但我沒有收到它 – gkn06
它會。它會在點擊按鈕時初始化。發佈更新的代碼 – Raghunandan