我正在使用 Eclipse 活动创建器中的标题条 + 滑动模板。这是我的片段代码:
public static class FactorFragment extends Fragment {
static EditText numHolder;
Button btnFactor;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Activity me = getActivity();
// Create the layout
// Create the views
RelativeLayout holder = new RelativeLayout(me);
numHolder = new EditText(me);
numHolder.setId(1);
btnFactor = new Button(me);
btnFactor.setId(2);
// Style the RelativeLayout
holder.setLayoutParams(new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
// Style the EditText
RelativeLayout.LayoutParams edittext = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
edittext.addRule(RelativeLayout.ALIGN_BOTTOM, btnFactor.getId());
edittext.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
edittext.addRule(RelativeLayout.LEFT_OF, btnFactor.getId());
numHolder.setEms(10);
numHolder.setInputType(InputType.TYPE_CLASS_NUMBER);
numHolder.setLayoutParams(edittext);
// Style the button
RelativeLayout.LayoutParams btn = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
btn.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
btn.addRule(RelativeLayout.ALIGN_PARENT_TOP);
btnFactor.setText("Factor");
btnFactor.setLayoutParams(btn);
btnFactor.setOnClickListener(onClick);
// Add them to the layout
holder.addView(numHolder);
holder.addView(btnFactor);
return holder;
}
static OnClickListener onClick = new OnClickListener() {
public void onClick(View v) {
int num = Integer.parseInt(numHolder.getText().toString());
Log.e("hi", Integer.toString(num));
}
};
}
如您所见,我正在创建一个名为 numHolder 的 EditText,它将保存数值。我遇到的问题是,当我单击按钮时,在此行出现强制关闭错误:
Log.e("hi", Integer.toString(num));
LogCat 告诉我Integer.toString()
无法解析空字符串。但是,从我在上面的行中获得 EditText 的内容这一事实,这让我相信 1)我使用错误的方法从 EditText 获取数字或 2)numHolder 是出于某种原因无法使用。
怎么了?几个小时以来,我一直试图弄清楚这一点。
编辑:
我static
从EditText
和 中删除了onClickListener
。它现在似乎起作用了。