我想以编程方式替换LinearLayout中的View。我尝试了以下方法:
public void drawView() {
//remove previous view, if exists
if(((LinearLayout) findViewById(R.id.chartView)).getChildCount() > 0) {
((LinearLayout) findViewById(R.id.chartView)).removeAllViewsInLayout();
}
//generate new view
CustomView view = new CustomView(this,parameters);
//add new view to layout
((LinearLayout) findViewById(R.id.linLayout)).addView(view);
}
此方法引用的LinearLayout在XML中定义:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linLayout">
</LinearLayout>
第一次正确绘制视图(当LinearLayout中还没有视图时。但第二次调用drawView时,前一个View被删除,但没有添加新视图。如何替换这个以编程方式生成的视图编程?
答案 0 :(得分:3)
您要从此布局中删除((LinearLayout) findViewById(R.id.linLayout)).addView(view);
但添加到此:R.id.linLayout
将R.id.chartView
替换为<html>
<body>
<table>
<tr><td>Text to Save:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" cols="80" rows="25"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
</table>
<script type="text/javascript">
function saveTextAsFile()
{
var textToSave = document.getElementById("inputTextToSave").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</body>
</html>