我有两个片段,我想使用界面来回调更改imageview 在第二个片段的第一个片段中,但是当回调被触发时,它的get imageview为null,我得到以下错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ImageView.setImageResource(int)' on a null object
reference
第一个片段:
public class firstfragment extends Fragment implements MyProfileCallback
{
Imageview myprofile_image;
public firstfragment()
{
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.fisrt, container, false);
myprofile_image=(ImageView) rootview.(find.id.myprofile_image);
/
...
/
}
@Override
public void callbackCall()
{
myprofile_image.setImageResource(R.drawable.profile_friends);
}
}
第二个片段:
public class secondfragment extends Fragment
{
MyProfileCallback mcallback;
public secondfragment()
{
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.second, container, false);
mcallback.callbackCall();
return rootview;
}
接口
public interface MyProfileCallback
{
void callbackCall();
}
答案 0 :(得分:1)
你的问题有点难以理解,你的代码也是如此,但我认为你应该在这种情况下加载资源文件R.drawable.profile_friends
当片段视图创建
你可以:
编辑: 您正在通过 onCreateView 方法调用回调,这意味着 mypfile_image 视图尚未引用您的元素 并且你得到一个空指针异常
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mcallback.callbackCall();
}