Reputation: 19
Hello i want to add onClick option in a Fragment to a ImageView. I tried a few things but failed. Here is my Fragmet.java
public class Info extends Fragment{
public Info() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.info, container, false);
}
}
Upvotes: 0
Views: 59
Reputation: 5589
You have to have an ImageView
in the layout R.layout.info.
If the ImageView
's id is ivInLayout
, you set an onClik
mehtod like this:
public class Info extends Fragment{
public Info() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.info, container, false);
ImageView iv = (ImageView) v.findViwById(R.id.ivInLayout);
iv.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(){
<What you want onClick on the image to do>
}
});
return v;
}
}
Upvotes: 0
Reputation: 1728
Instead of returning the view directly ,do this
View v=inflater.inflate(R.layout.info, container, false);
you can then use v to find reference to your ImageViews
ImageView iv=(ImageView)v.findViewById(R.id.imageview_id);
then set onClickListener as usual
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//do something
}
});
Upvotes: 0
Reputation: 157447
Override
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
and use the view
object, which is the same View
you are returning in onCreateView
, to look for the ImageView on which you want to set your onClickListener
. E.g.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
View imageView = view.findViewById(R.id.id_of_image_view);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
Upvotes: 1