Solution 1 :
Inflate your fragment like this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_timer, container, false);
}
Problem :
My code worked when I had it in MainActivity but then when I tried to use it in a fragment it wont work because I can’t extend AppCompatActivity. Is there anyway I can fix my code for it to work in this fragment without extending AppCompatActivity and if so, how?
Timer.java
public class Timer extends Fragment {
private static final long START_TIME_IN_MILLIS = 600000;
private TextView mTextViewCountDown;
private Button mButtonStartPause;
private Button mButtonReset;
private CountDownTimer mCountDownTimer;
private boolean mTimerRunning;
private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_timer);
mTextViewCountDown = findViewById(R.id.text_view_countdown);
mButtonStartPause = findViewById(R.id.button_start_pause);
mButtonReset = findViewById(R.id.button_reset);
mButtonStartPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mTimerRunning) {
pauseTimer();
} else {
startTimer();
}
}
});
mButtonReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetTimer();
}
});
updateCountDownText();
}
Comments
Comment posted by Vivek Mishra
That’s not how fragments are inflated. You should first read about how fragments work
Comment posted by here
As @VivekMishra mentioned, you can’t inflate layout in