Reputation: 929
I have looked through most of the questions I could find for a solution to this but none of the suggestions have seemed to be my issue. I've tried cleaning and rebuilding the project and restarting android studio. made sure inflating is done before I attempt to retrieve the UI elements and I've tried placing findViewById several different methods. Here's how I think it should be (but still doesn't work). I have also attempted retrieving other view in the parent activity's on Create after committing the fragment transaction. Also without success.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.search_fragment,container,false);
seekBarDuration = (SeekBar) getActivity().findViewById(R.id.seekBarDuration);
return v;
}
@Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
seekBarDuration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
App crashes at the last line because seekBarDuration is a null reference. the Seekbar is located in the fragment's own layout.
Upvotes: 0
Views: 255
Reputation: 838
Hi you are trying to get it from the Activity when you have stated that your view is on the fragment`, change your code like to this.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.search_fragment,container,false);
seekBarDuration = (SeekBar) v.findViewById(R.id.seekBarDuration);
//Also set listener in here since seekBarDuration is on the Fragment not in Activity
seekBarDuration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {});
return v;
}
@Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//This is called when the Activity is created, not the fragment.
}
I also changed where you set the listener
you can either leave it inside the @onCreateView
or make the Fragment
implement it and set it like seekBarDuration.setOnSeekbarChangeListener(this);
Hope it helps.
More info on the Documentation
Upvotes: 2
Reputation: 1006604
Do not call findViewById()
on getActivity()
in onCreateView()
. Call it on the View
that you just inflated.
IOW, replace:
seekBarDuration = (SeekBar) getActivity().findViewById(R.id.seekBarDuration);
with:
seekBarDuration = (SeekBar) v.findViewById(R.id.seekBarDuration);
Upvotes: 4