Reputation: 357
I'm trying to convert a layout so that it will include fragments. One of the views is an ImageButton that has a listener. The code worked fine as an Activity but makes trouble as a Fragment...
First problem was that I couldn't use findViewById, but I was able to find the answer for that here and fixed it with getView().
I can't find an answer to the second problem... after I declared:
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
I want to set an on click listener:
camBt.setOnClickListener(listener);
But it keeps acting like the ImageButton (camBt) doesn't exist... I don't even know what's the problem... it worked fine in the Activity...
Here's the full code. Many thanks!
public class CameraFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.camera_fragment, container, false);
return V;
}
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
camBt.setOnClickListener(listener);
ImageButton.OnClickListener listener = new ImageButton.OnClickListener()
{
@Override
public void onClick(View arg0)
{
Camera.open().getParameters();
}
};
}
Upvotes: 3
Views: 6826
Reputation: 3513
public class CameraFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.camera_fragment, container, false);
ImageButton camBt = (ImageButton)V.findViewById(R.id.button1);
ImageButton.OnClickListener listener = new ImageButton.OnClickListener()
{
@Override
public void onClick(View arg0)
{
Camera.open().getParameters();
}
};
camBt.setOnClickListener(listener);
return V;
}
}
Upvotes: 0
Reputation: 47807
You should add
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
camBt.setOnClickListener(listener);
inside onCreateView()
like:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.camera_fragment, container, false);
ImageButton camBt = (ImageButton)v.findViewById(R.id.button1);
camBt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
return V;
}
Upvotes: 0
Reputation: 82938
Move
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
camBt.setOnClickListener(listener);
inside onCreateView()
.
Like
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.camera_fragment, container, false);
// Here it is
ImageButton camBt = (ImageButton)v.findViewById(R.id.button1);
camBt.setOnClickListener(listener);
return v;
}
And one more thing you need to understand that variable name should starts with small letter. So you should use View v
instead of View V
.
Upvotes: 9