In my app I use some Fragments with some Buttons that help to navigate through different contents. The layout I built works perfectly, but now i want to make the links for the Buttons.
MY BUTTON ID IS: buttonSP
Where can I add the onClickListener in my code snippet to open a new Activity named: Lista_Smartphone?
FragmentWithOneImage.java
public class FragmentWithOneImage extends Fragment {
private String title;
private int image;
public static FragmentWithOneImage newInstance(String title, int resImage) {
FragmentWithOneImage fragment = new FragmentWithOneImage();
Bundle args = new Bundle();
args.putInt("image", resImage);
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
image = getArguments().getInt("image", 0);
title = getArguments().getString("title");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_img, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.txtMain);
tvLabel.setText(title);
ImageView imageView = (ImageView) view.findViewById(R.id.imgMain);
imageView.setImageResource(image);
return view;
}
}
答案 0 :(得分:0)
在 onCreateView()方法中添加以下代码
void q3():{}
{
q0() | <END>
}
答案 1 :(得分:0)
将它放在onCreateView()方法上。它等同于活动类的onCreate()
答案 2 :(得分:0)
使用onActivityCreated()
方法,有时在onCreateView()
中查找视图需要花费时间,在这些情况下可能会出现空指针异常。
public class FragmentWithOneImage extends Fragment {
TextView tvLabel;
ImageView imageView;
Button button;
public static FragmentWithOneImage newInstance(String title, int resImage) {
FragmentWithOneImage fragment = new FragmentWithOneImage();
Bundle args = new Bundle();
args.putInt("image", resImage);
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_img, container, false);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvLabel = (TextView) view.findViewById(R.id.txtMain);
imageView = (ImageView) view.findViewById(R.id.imgMain);
button=(Button)view.findViewById(R.id.button);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tvLabel.setText(title);
imageView.setImageResource(image);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getActivity(),Lista_Smartphone.class);
startActivity(intent);
}
});
}
}