【问题标题】:A problem with initializing textView in fragment在片段中初始化 textView 的问题
【发布时间】:2021-04-05 18:25:59
【问题描述】:

当我开始活动时,我也开始片段

conversion_1 = new Conversion();

fragment中有一个OnCreateView

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_conversion, container, false);
        curr_to_txt_1 = view.findViewById(R.id.curr_to_txt);
        curr_to_txt_1.setText("rrr");
        return view;
    }

当我调用 curr_to_txt_1.setText("text"); 时,它在 OnCreateView 中工作,但如果我稍后在 void 函数中调用它,应用程序将停止(该函数在活动中调用并且函数本身工作)

public void set_curr_to_txt() {
        curr_to_txt_1.setText("rrr");
    }

说curr_ro_text为空,但已经初始化了

【问题讨论】:

  • 使用 onViewCreated()。
  • 如果您从活动中调用此方法,请确保已调用片段上的 onViewCreated
  • @Eyosiyas @Override public void onViewCreated (View view, Bundle savedInstanceState){ curr_to_txt_1 = (TextView) view.findViewById(R.id.curr_to_txt); super.onViewCreated(view, savedInstanceState); } 我做到了,但还是同样的问题

标签: java android view fragment


【解决方案1】:

我觉得……

您可以使用 onViewCreated 创建 'curr_to_txt_1' 而不需要视图变量。

public class Test extends Fragment {


private TextView text;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.test_layout, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    /*
    * Write your bind here
    * */
    text=view.findViewById(R.id.view_id);
}

}

考虑到fragmentlife cycle,在onViewCreated中,fragment存在并且可以与组件绑定

有任何问题,我很乐意为您提供帮助!

【讨论】:

  • 与组件绑定是什么意思?很抱歉提出愚蠢的问题,我只是一个初学者
  • 没问题 :),我是来帮你的,当你调用 'findViewById' 时,你说 android 在这个变量中绑定这个元素,明白吗?抱歉耽搁了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 2023-02-15
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多