将fragment的参数传到mainActivity中

day_moon 2016-01-11 06:16:22
1、一个fragment1类,代码如下:

public static final int PAGE_SIX=5;
public void onClick(View v) {
switch (v.getId()) {
case R.id.ib_update: //点击到该按钮时
mButtonInterface.onButtonSelect(PAGE_SIX); //调用下面的接口进行传值
break;
}
}

//定义一个接口
private buttonSelectInterface mButtonInterface;
public interface buttonSelectInterface {
public void onButtonSelect(int button);
}


2、mainActivity类中继承buttonSelectInterface:

//传递过来的参数
@Override
public void onButtonSelect(int button) {
switch(button){
case PAGE_SIX:
vpager.setCurrentItem(PAGE_SIX);
break;
}
}
跪求大神!!!
问题:调试发现点击按钮时,可以看到一个fragment1类中的值是5(由于接口不能设置断点,没看到在fragment1类中的接口botton的值,红色部分),但是在mainActivity类中,botton的值是没有的。也就是说fragment1类中
接口的值没有传到mainactivity过来。
...全文
259 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
day_moon 2016-01-15
  • 打赏
  • 举报
回复
已经继承了。害死没有。可是运行就是报错。代码我已经贴出了。
雨焰 2016-01-12
  • 打赏
  • 举报
回复
引用 2 楼 day_moon 的回复:
在Fragment1中添加下面代码: public void setListener(buttonSelectInterface button){ this.mButtonInterface = button; }; mainactivity类的onCreate方法中添加: fragment1 = new MyFragment1(); fragment1.setListener(this); 调试发现,Fragment1类中还是没有值。
你有在Activity中实现fragment的接口吗? 在fragment中有将Activity赋值给你的listener吗? 这两个都要有的
_周星星 2016-01-12
  • 打赏
  • 举报
回复
难道不能用Intent传值?
day_moon 2016-01-12
  • 打赏
  • 举报
回复
在Fragment1中添加下面代码: public void setListener(buttonSelectInterface button){ this.mButtonInterface = button; }; mainactivity类的onCreate方法中添加: fragment1 = new MyFragment1(); fragment1.setListener(this); 调试发现,Fragment1类中还是没有值。
柒加伊 2016-01-11
  • 打赏
  • 举报
回复
你继承接口有什么用啊. 你这是对接口不熟悉的问题啊... 给你改一下吧. fragment1里面: public static final int PAGE_SIX=5; public void onClick(View v) { switch (v.getId()) { case R.id.ib_update: //点击到该按钮时 mButtonInterface.onButtonSelect(PAGE_SIX); //调用下面的接口进行传值 break; } } //定义一个接口 private buttonSelectInterface mButtonInterface; public interface ButtonSelectInterface { public void onButtonSelect(int button); } publict void setListener(ButtonSelectInterface interface){ this.mButtonInterface = interface; }; mainActivity里面: class extends Activity implements buttonSelectInterface { onCreate(...) { fragment1 = new Fragment1(); fragment1.setListener(this); } //传递过来的参数 @Override public void onButtonSelect(int button) { switch(button){ case PAGE_SIX: vpager.setCurrentItem(PAGE_SIX); break; } } 这回就好用了...

80,471

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧