【发布时间】:2019-08-27 07:45:14
【问题描述】:
我在 android studio 工作,想为 CalendarView 对象设置 setOnDateListener。 CalendarView 对象位于以编程方式生成的片段内。唯一的问题是尝试将数据从日历发送到MainActivity 文件时。它一直在说空对象引用。
我什么都试过了。目前我正在尝试使用我没有经验的界面。我试过到处移动听众。似乎没有任何效果。这是最小的(非常抱歉)
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentEntry.Callback {
FragmentHome fragmentHome;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// add the fragments
adapter.addFragment(new FragmentHome(), "Home");
adapter.addFragment(new FragmentEntry(), "Entry");
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
public void sendDate(int day, int month, int year)
{
fragmentHome.text(day, month, year);
}
}
FragmentHome:
public class FragmentHome extends Fragment {
// empty constructor, onCreate, and onCreateView
public void text(int day, int month, int year) {
TextView textView = getText().findViewById(R.id.textView);
String text = String.format(R.string.month + "/" + R.string.day + "/" + R.string.year, month, day, year);
textView.setText(text);
}
}
片段条目:
public class FragmentEntry extends Fragment {
public Callback callback;
// empty constructor, onCreate
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_entry, container, false);
CalendarView calendarView = v.findViewById(R.id.calendarView);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView calendarView, int y, int m, int d) {
callback.sendDate(d, m, y);
}
return v;
}
就像我说的那样,我尝试过在日期监听器周围移动,但它目前就在这里。我希望 sendDate 函数调用能够正常运行,但 Logcat 另有说明。一直在说
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.fragmentcommunicationtest.FragmentEntry$Callback.sendDate(int, int, int)' on a null object reference
即使不使用接口,我对整个空对象引用也有同样的问题。我不知道还能去哪里。我已经尝试了一切,我希望在这一点上它会成为我忽略的东西。帮助
【问题讨论】:
-
你需要初始化你的回调。请显示您从
MainActivity创建FragmentHome的代码。 -
@sunilsunny 按要求添加了片段主页实现。
-
好的,看看我的回答。
-
我注意到的另一个错误是
getText().findViewById(R.id.textView);。你找不到那样的风景。 -
@sunilsunny 我的错,意思是说
getView()。我的错。
标签: java android android-fragments event-listener