【发布时间】:2014-10-22 23:03:18
【问题描述】:
当我使用setTag() 动态设置View 的标签时,它不会在方向更改后保留。几个相关问题的答案(特别是这两个答案 - 1 和 2)似乎表明标签在方向更改时保持不变(如果 View 存储在标签中,则内存泄漏意味着它不是当它应该被释放时 - 即方向改变)。有没有办法在方向改变后保留View 标签(除了物理实现你自己的方法)?
我已经完成了一个简单的示例,其中标签不会在方向更改时保存。第一个Button用于设置第二个Button的标签。第二个Button 在单击时显示其当前标签。在方向改变时,标签是 always null:
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.set_tag).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
findViewById(R.id.display_tag).setTag("MY VIEW TAG");
Toast.makeText(Main.this, "Tag set!", Toast.LENGTH_SHORT).show();
}
});
findViewById(R.id.display_tag).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s = (String) findViewById(R.id.display_tag).getTag();
Toast.makeText(Main.this, "Tag is: "+((s == null) ? "null" : s), Toast.LENGTH_SHORT).show();
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/set_tag"
android:text="Set Tag"
android:freezesText="true"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/display_tag"
android:text="Display Tag"
android:freezesText="true"/>
</LinearLayout>
定向之前:
帖子方向:
【问题讨论】:
标签: android android-view android-orientation