我是android开发的初学者,当我单击ImageView中的图像时,我想从片段导航到活动。我的Java类不允许我声明变量以链接到我的XML文件。另外,我不确定应该在哪个Java类中声明变量。
我也尝试过在MainActivity中编写相同的代码,但仍然显示错误。
public class HomeFragment extends Fragment{
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home,container,false);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edSheeranSongs = (ImageView)findViewById(R.id.ed_sheeran);
justinBieberSongs = (ImageView)findViewById(R.id.justin_bieber);
shawnMendesSongs = (ImageView)findViewById(R.id.shawn_mendes);
edSheeranSongs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),SheeranSongs.class);
startActivity(intent);
}
});
我希望继续进行已经创建的另一个活动,称为SheeranSongs,但是当我尝试在片段中声明任何内容时,我会收到一条错误消息
答案 0 :(得分:0)
您应该从 Fragment 的@media print { //your css code }
中的膨胀视图调用findViewById()
。范例:
onCreateView
答案 1 :(得分:0)
您应该在片段的onCreateView
中扩展视图,并使用创建的自定义视图初始化视图。覆盖onAttach
以获取该片段所附加到的活动的上下文。
public class HomeFragment extends Fragment{
private Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
edSheeranSongs = view.findViewById(R.id.ed_sheeran);
justinBieberSongs = view.findViewById(R.id.justin_bieber);
shawnMendesSongs = view.findViewById(R.id.shawn_mendes);
edSheeranSongs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, SheeranSongs.class);
startActivity(intent);
}
});
return view;
}
}
答案 2 :(得分:0)
使用片段时,您无法像在Activity中那样在onCreate()中调用findviewbyid(),因为片段是在onCreate()中创建的,但尚未绘制用户界面(More about fragment)。 您可以在onCreateView()或onViewCreated()中进行操作。从我的角度来看,我是在onViewCreated()中完成的,因此它看起来更干净了。
public class HomeFragment extends Fragment{
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home,container,false);
}
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView edSheeranSongs = view.findViewById(R.id.ed_sheeran);
ImageView justinBieberSongs = view.findViewById(R.id.justin_bieber);
ImageView shawnMendesSongs = view.findViewById(R.id.shawn_mendes);
edSheeranSongs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(requireActivity(), SheeranSongs.class);
startActivity(intent);
}
});
}