维持方向更改时动态设置View标签

时间:2014-10-22 23:03:18

标签: android android-view android-orientation

当我动态设置View setTag()的标记时,在方向更改后不会保留该标记。几个相关问题(特别是这两个答案 - 1& 2)的答案似乎表明标签是在方向更改时保留的(如果存储了View则会出现内存泄漏在标签中意味着它应该在它应该被释放时 - 即方向改变)。有没有办法在方向更改后保留View标签(除了物理实现自己的方法)?

我已经完成了一个简单的示例,其中标签未在方向更改时保存。第一个Button用于设置第二个Button的标记。第二个Button在单击时显示其当前标记。在方向更改时,标记始终 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>

入职前: Prior to orientation - with tag

发布方向: After orientation - no tag

1 个答案:

答案 0 :(得分:0)

我不认为标签真的是你想要的。考虑使用onSaveInstanceStateonRestoreInstanceState来保留在销毁和重新创建活动时需要保留的所有数据。

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putString("tag", message);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(state);
    message = state.getString("tag");
}
相关问题