java - 在 fragment 中执行操作

标签 java android android-fragments android-fragmentactivity

我在理解 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_statusTextView,这将起作用。

关于java - 在 fragment 中执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11715225/

相关文章:

Android: fragment backStack

java - 如何从返回文件名及其文件夹名称的文件夹中递归检索文件

android - 无法从 Android socket.io 2 客户端连接到 node.js socket.io 3.x 服务器

android - 在抽屉导航中单击返回时操作栏上的双项

android - 可绘制土地与可绘制土地

java - 为什么我的 AlarmManager 不触发 BroadcastReceiver

java - fragment 中的Android getActivity(), getApplicationContext()

java - 从 python 到 stdin java 的 stdout

java - 滑动时的 Android ViewPager Bug

java - 绑定(bind)不匹配缓解