【问题标题】:How to use a method within a fragment?如何在片段中使用方法?
【发布时间】:2013-10-13 02:59:49
【问题描述】:

我正在尝试编写一个片段,该片段具有在 TextView 中设置某些内容的方法。所以我有以下片段:

public class DetailFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.my_fragment, container, false);
//    setText("set it to something");
    return view;
  }

  public void setText(String item) {
    TextView view = (TextView) getView().findViewById(R.id.detailsText);
    view.setText(item);
  }
}

这很好用。它显示了文本视图。我现在想以编程方式编辑 textview 中的文本。我想我首先要从片段中编辑它。所以我有了应该能够做到的方法。当我现在取消注释setText("set it to something");时,它给了我一个InflateException: Error inflating class fragment.,我不知道为什么。

有人知道我该如何解决这个问题吗?

【问题讨论】:

  • 在 onResume 中调用你的方法
  • @Waqas - 谢谢。确实像一个魅力!其他人还建议在 onCreateView 中执行其他方法。哪一种是最好/正确的方法;在 onCreateView 中还是在 onResume 中?
  • 在onResume() 中执行此操作将导致每次暂停和恢复片段时都会调用此方法,这很糟糕,因为有时片段只是暂停和恢复(当显示对话框时)在这种情况下它无缘无故重新设置文本不是一个好主意。我建议您将此电话转至onViewCreated() 或onActivityCreated()。
  • @M-WaJeEh 我知道我的建议是一个快速的解决方案。从技术上讲,它应该在 onActivityAttached 中调用 :)

标签: java android xml android-fragments


【解决方案1】:

这样做

class ... extends Fragment{
   private TextView _myTextView;

   onCreateView(...){
       //inflate view

       _myTextView = (TextView)view.findViewById(R.id.text_view);
       editText("blablabla");
   }


   private void editText(String text){
       _myTextView.setText(text);
   }
}

Ypu 必须在 onCreateView 中初始化所有 UI 元素,以便从正在膨胀的视图中膨胀!

【讨论】:

    【解决方案2】:

    如果您想在onCreateView() 中执行此操作,请执行以下操作:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                 Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_fragment, container, false);
        TextView tv= (TextView) view.findViewById(R.id.detailsText);
        tv.setText("set it to something");
        return view;
    

    }

    原因是在返回onCreateView()之前无法调用getView()。

    或从onViewCreated():

    public void onViewCreated (View view, Bundle savedInstanceState){
        TextView tv = (TextView) view.findViewById(R.id.detailsText);
        tv.setText("set it to something");
        // following will work too here
        // setText("set it to something");
    }
    

    【讨论】:

    • 好的,谢谢! Waqas 在 onResume 中也提出了这样做的建议。从您建议的 onCreateView 或 onResume 方法中,最好/正确的方法是什么?
    • 还有一个问题;我想要一个专用方法来更改此文本的原因是因为我实际上希望能够从 Activity 中调用它。你知道怎么做吗?
    • 那么您应该从onViewCreated() 调用它,或者可能从onActivityCreated() 调用它。在onResume() 中执行此操作将导致每次暂停和恢复片段时都会调用此方法,这很糟糕,因为有时片段只是暂停和恢复(显示对话框时),在这种情况下设置无缘无故再次发短信。
    • 我尝试在我的片段中创建 onViewCreated() 和 onActivityCreated(),但它抱怨这些不是片段的超类型方法。关于如何做到这一点的任何想法/示例?
    • 如果您使用的是 eclipse,那么只需在要插入方法的地方写上onView,按 ctrl+space 并从选项中选择方法。 onActivityCreated() 也是如此。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    相关资源
    最近更新 更多