【问题标题】:Android Studio Fragments I can't get data [closed]Android Studio Fragments我无法获取数据[关闭]
【发布时间】:2018-01-27 23:00:59
【问题描述】:

当我在 Android Studio 中使用 Fragments 时,在 Fragment 文件中我不能使用例如:TextView textViewToChange = (TextView) findViewById(R.id.rate);

我无法从输入中获取值,我的班级是public class MainActivity extends Fragment{}

【问题讨论】:

  • 请详细说明...片段不存在于活动中。 MainActivity extends Fragment怎么样??
  • 请分享代码,以便其他人能够找到问题。

标签: java android android-studio android-fragments navigation-drawer


【解决方案1】:

解决方案

Activity#findViewById (int id)Activity 类的方法,而Fragment 既不是它的子类也不是超类。

解决方案是在onCreateView()的膨胀视图上使用View#findViewById (int id)

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    TextView textViewToChange = (TextView) view.findViewById(R.id.rate);
    return view;
  }

另类

另外作为替代,我建议使用Butterknife 来绑定视图。您只需使用 @BindView 注释该字段并调用 ButterKnife.bind(this, view) 并且库会生成样板代码而不是您编写它。 注意:在 Activity 中使用 ButterKnife.bind(this)。

这是他们网站上的代码示例:

public class FancyFragment extends Fragment {
  @BindView(R.id.rate) TextView textViewToChange;  //it is automatically cast to TextView
  @BindView(R.id.button) Button button;  //or a button

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    ButterKnife.bind(this, view);  //do not forget this!
    // TODO Use fields...
    return view;
  }
}

【讨论】:

  • 不要让库的答案过于复杂。请确保您以提问的方式回答,即此处没有 ButterKnife
  • @NileshSingh 我希望重新格式化、重新排列和完成的答案现在更符合您的喜好:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
相关资源
最近更新 更多