我有一个应用程序,按下按钮点击3个不同的片段,即MainActivity - > (MainActivity)按钮按下 - >片段1 - > (片段1)按钮按下 - >片段2等我试图创建一个已访问的片段的日志,即使应用程序关闭也可以存储。因此,如果访问了所有片段,则日志将显示:"片段1,片段2,片段3"
简而言之,我的问题是如何记住每个片段中的数据以创建日志,即使应用程序被杀死,如何将此日志保存在应用程序的内存中。下面显示了主要活动以及其中一个片段(现在所有片段都是相同的)
主要活动:
public class MainActivity extends AppCompatActivity {
Button start_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get button references
start_button = (Button)findViewById(R.id.new_home);
start_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadFragment(new FirstFragment());
start_button.setVisibility(View.GONE);
}
});
}
public void loadFragment(Fragment fragment) {
//create fragment manager
FragmentManager fragmentManager = getSupportFragmentManager();
//create a fragment transaction to begin the transaction and replace the fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//replace the frame layout with new fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit();//save the changes
}
}
FRAGMENT:
public class FirstFragment extends Fragment {
View view;
Button firstButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//inflate the layout for the fragment
view = inflater.inflate(R.layout.fragment_first,container,false);
firstButton = (Button)view.findViewById(R.id.firstButton);
firstButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Activity Logged",Toast.LENGTH_SHORT).show();
///////////LOG FRAGMENT HERE////////////////////////////////
((MainActivity) getActivity()).loadFragment(new Fragment2());
}
});
return view;
}
}
答案 0 :(得分:0)
使用此方法写入文本文件(默认情况下,此方法写入默认下载文件夹).Params是1.要写入的数据2.要存储的目录3.带扩展名的文件名(.txt用于文本文件)
将此方法放在父活动中
public void writeToFile(String data,String Dir,String FileName) {
try {
File dir=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/"+Dir);
Log.d(TAG,"Dir "+dir);
if (dir.exists() == false) {
dir.mkdirs();
}
final File file = new File(dir, FileName);
Log.d(TAG,"File Path "+file);
FileOutputStream fOut = new FileOutputStream(file,true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.flush();
myOutWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
并从你的片段中这样调用:
((MainActivity)getActivity()).writeToFile("Fragment1","MyLog","TrackLog.txt");