【问题标题】:Android: In the fragment class, on accessing a variable of Activity class through it's getter method, the variable's value remains 0Android:在fragment类中,通过它的getter方法访问Activity类的变量,变量的值保持为0
【发布时间】:2018-10-10 13:46:34
【问题描述】:

Activity类在onCreate方法中有一个整数,通过getIntent设置。

    pos = getIntent().getIntExtra("position", -1); 

-1 是 getIntExtra() 的默认值,“position”是我将它存储在另一个类中的键。对于点击来说,这个值应该是动态的,而且确实如此。 但是,在通过 Activity 的 getpos() 方法在片段类中访问它时,它总是返回 0。 为什么?

这是 Acitivity 类的 OnCreate 方法:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        pos = getIntent().getIntExtra("position", -1);}

这是 Acitivity 类的 pos 的 getter 方法:

public int get(){
        return pos;
    }

这是 Fragment 的 onCreateView 方法:

//an inflater
    Activity my=(Activity) getActivity();
    int posfrag = my.get();

我正在尝试通过此访问 Recycler View 的项目位置,但是这里的 posfrag 没有在片段中更新,尽管 pos 在 Activity 方法中正确更新。问题在于将保留的值传递给片段。

【问题讨论】:

  • 你能显示更多代码吗?我很难想象你在做什么以及你在做什么。
  • 分享更多代码块
  • 抱歉,更新了我的问题
  • get 函数返回的这个“位置”变量是什么?变量不是叫“pos”吗?
  • 是的,是同一个@Bal0r

标签: java android android-fragments android-intent


【解决方案1】:

尝试在 Fragment 中的 onActivityCreated() 方法中获取 pos 值。

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    // retrieve your variable value here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2023-04-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    相关资源
    最近更新 更多