我有一个程序片段,是一个“计时器”,它可以添加在任何地方。在片段中我以程序的方式改变一个textView,它可以很好的运行。我的问题是当从布局中使用一个视图时,如何在片段下面的另外一个方法中用构造函数实现?
public class Timer_fragment extends android.support.v4.app.Fragment {
int testpins;
String testedpin;
TextView text;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.timer_frag, container, false);
TextView text = (TextView) v.findViewById(R.id.pwd_status);
text.setText("Setting text in fragment not main");
/* set the TextView's text, click listeners, etc. */
updateStatus();
return v;
}
所有这些代码都能很好的运行,但是当我添加下面这段代码时,
private void updateStatus() {
TextView text = (TextView) findViewById(R.id.pwd_status);
testPin();
text.setText(testedpin);
}
indViewById下面会出现红线说findViewById(int)方法不是Timer_fragment类型
在你的代码段落中已经有一个成员变量text。不要在方法中重新声明这个成员变量,只需分配它。
text = (TextView) v.findViewById(R.id.pwd_status);
and
private void upateStatus() {
testPin();
text.setText(testedpin);
}
传递Activity的一个实例到Timer_fragment:
private final Activity _activity;
Timer_fragment(Activity activity)
{
_activity = activity;
}
...
private void updateStatus()
{
TextView text = (TextView) _activity.findViewById(R.id.pwd_status);
testPin();
text.setText(testedpin);
}