我有一个位图,我想将其保存到应用程序文件夹中。我尝试使用这些代码:
ContextWrapper contextWrapper = new ContextWrapper(context.getApplicationContext());
File directory = contextWrapper.getDir("tabs", Context.MODE_PRIVATE);
if (!directory.exists())
directory.mkdir();
String fname = "Image.jpg";
File file = new File(directory, fname);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.close();
} catch (Exception e) {
Log.e("SAVE_IMAGE", e.getMessage(), e);
}
Run Code Online (Sandbox Code Playgroud)
现在,我有两个问题。
“File.mkdir()”的结果被忽略
我正在通过https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin的示例项目 RoomWordsSample 学习 Room。
以下代码来自项目。
在我看来,如果观察到数据发生变化,LiveDate 将自动更新 UI。
但是在文件 WordListAdapter.kt 中,我发现notifyDataSetChanged()添加到function setWords(words: List<Word>)? 似乎它必须在数据更改时手动通知 UI。
为什么还需要启动 notifyDataSetChanged()当我使用 LiveData 时,?
主活动.kt
class MainActivity : AppCompatActivity() {
private val newWordActivityRequestCode = 1
private lateinit var wordViewModel: WordViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
val adapter = WordListAdapter(this)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)
wordViewModel.allWords.observe(this, Observer { words ->
words?.let { adapter.setWords(it) }
})
}
}
Run Code Online (Sandbox Code Playgroud)
WordViewModel.kt …