【发布时间】:2016-08-12 13:58:48
【问题描述】:
我必须在自定义适配器中定义的 MainActivity 中实现一个接口。但是该接口方法的所有相关对象都在片段中定义。那么如何在 MainActivity 和 Fragment 之间进行通信,以使接口的实现工作而不会出现空指针异常呢?
这是我必须实现的接口,它在自定义适配器中定义。
public interface UpdateMainClass{
void updateItemList(int position);
void updateListBackground(int position, boolean isChecked);
}
在我的主要活动中,我覆盖了上述内容。
/**
* <p>This method is used to remove the item from speicified position</p>
* @param position location of the item to be removed
*/
@Override
public void updateItemList(int position) {
myNewFragment.updateItemList(position);
}
/**
* <p>Updates the background checkbox status in POJO class and helps to set the background color on long press.</p>
* <p>Illegal state is checked to prevent changing of checkbox status while list is being scrolled.</p>
* @param position position of the item in list where checkbox status is changed.
* @param isChecked current status of the checkbox.
*/
@Override
public void updateListBackground(int position, boolean isChecked) {
myNewFragment.updateListBackground(position, isChecked);
}
这是我的 Fragment 类,我可以在其中实际实现该方法。
/**
* <p>This method is used to remove the item from speicified position</p>
*
* @param position location of the item to be removed
*/
public void updateItemList(int position) {
myArrayList.remove(position);
mAdapter.notifyItemRemoved(position);
}
/**
* <p>Updates the background checkbox status in POJO class and helps to set the background color on long press.</p>
* <p>Illegal state is checked to prevent changing of checkbox status while list is being scrolled.</p>
*
* @param position position of the item in list where checkbox status is changed.
* @param isChecked current status of the checkbox.
*/
public void updateListBackground(int position, boolean isChecked) {
try {
if (isChecked)
myArrayList.get(position).setCompleted(1);
else
myArrayList.get(position).setCompleted(0);
mAdapter.notifyItemChanged(position);
} catch (IllegalStateException e) {
//do nothing
}
}
这显然不起作用,我最终在我的片段类中的myArrayList.get(position) 处得到一个空指针异常。那么有没有更好的编码方式呢?
【问题讨论】:
-
你想从片段访问活动方法??
-
其实是相反的
标签: android android-fragments interface