I wanted to add Stopwatch in a fragment with bottom navigation activity but findviewbyid shows error. I tried View...., and getView() but nothing works. Please tell some solution to the problem.
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
public class StopwatchFragment extends Fragment {
private StopwatchFragment(){
}
private Chronometer chronometer;
private boolean running;
private long pauseOffset;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState ){
return inflater.inflate(R.layout.fragment_stopwatch, null);
}
chronometer = **findViewById**(R.id.cm);
public void startChronometer(View view){
if (!running){
chronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
chronometer.start();
running = true;
}
}
public void pauseChronometer(View view){
if (running){
chronometer.stop();
pauseOffset = SystemClock.elapsedRealtime() - chronometer.getBase();
running = false;
}
}
public void resetChronometer(View view){
chronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
}
}
This is my Java code where findViewById shows invalid method declaration, missing method body etc.... Please Help!
findViewByIdmust be declared inside the method. In your case, it is out of any declared one.Declaring that line at the start of
startChronometershould work: