我正在尝试构建一个带有 3 个标签作为片段的小录音应用程序。我了解到,当我启动应用程序时,将使用 onCreateView 创建 2 个选项卡。起初,我希望每次切换 Fragment 时都会调用 PlaceHolderFragment 中的 onCreatView 以显示新的 Fragment。(这是我为录音而扩展的 Android Studio 中的简单 Fragment Acitivty Demo)。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
Integer section = getArguments().getInt(ARG_SECTION_NUMBER);
switch (section) {
case 1:
rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
final TextView timeView;
timeView = (TextView) rootView.findViewById(R.id.timeView);
//Button start_stop;
final Button start_stop = (Button) rootView.findViewById(R.id.button);
start_stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity mainAct = (MainActivity) getActivity();
if (recorder == null) {
recorder = new MediaRecorder();
}
if (mainAct.running) {
recorder.stop();
start_stop.setText("start recording");
mainAct.running = false;
mainAct.time = 0;
} else {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//recorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrecording.mp3");
recorder.setOutputFile(getActivity().getApplicationContext().getFilesDir() + "/audio.mp3");
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
recorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
mainAct.running = true;
mainAct.initThread(timeView);
start_stop.setText("stop recording");
}
}
});
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_sound, container, false);
break;
case 3:
rootView = inflater.inflate(R.layout.fragment_pics, container, false);
break;
default:
rootView = null;
break;
}
return rootView;
}`
记录的持续时间将显示在 TextView 中。时间在新线程中更新。
public void initThread(final TextView timeView) {
refreshThread = new Thread(new Runnable() {
public void run() {
while (running) {
time = time + 0.1;
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
}
runOnUiThread(new Runnable() {
public void run() {
timeView.setText(getString(R.string.time_string, String.format("%.1f", time)));
}
});
}
}
});
refreshThread.start();
}
到目前为止一切正常 - 当我在第一个选项卡(显示持续时间)时正在运行录制 - 即使我切换到第二个选项卡也是如此。但是当我切换到第三个选项卡并返回第一个选项卡时,持续时间不再显示。
确切:当我从 Tab 1 到 Tab 2 并返回到 Tab 1 时,时间仍在按预期更新。从 Tab 1 到 Tab 2 到 Tab 3 再回到 Tab 2 和 Tab 1 一切似乎在这个屏幕上都是初始的。时间将不再更新 - TextView 具有初始文本。我调试了应用程序,当从 Tab 3 返回时,威胁仍在运行,但 TextView 不会获得当前持续时间。
有人可以给我这个行为的提示吗?我认为当转到 Tab 3 时,Tab 1 的片段将被破坏 - 但在切换到 Tab 1 时它将再次构建。
如何解决这个问题?
谢谢