我在理解 fragment 如何与 Activity 交互方面遇到了一些困难。
我的主要 Activity 是添加 fragment 。调用的 fragment 类在这里:
public class Timer_fragment extends android.support.v4.app.Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.timer_frag, container, false);
}
}
正在膨胀的布局内部有一个 textView,但在 fragment 类内部我无法“访问”它。
为什么我不能在 return 语句下方添加 TextView text = (TextView) findViewById(R.id.pwd_status);
?
这对我来说很有意义,因为如果我想在很多地方添加计时器并以编程方式更改一件事,那么它会随处更改。希望这是有道理的。
谢谢
答案:
我只是保持 onCreateView 不变并添加了 onActivityCreated。然后我就可以像往常一样做一切事情了。
最佳答案
你可以这样做:
@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);
/* set the TextView's text, click listeners, etc. */
return v;
}
假设您的 timer_frag
布局中有一个 ID 为 pwd_status
的 TextView
,这将起作用。
关于java - 在 fragment 中执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11715225/