在显示旋转后恢复表单中的值

时间:2012-11-14 12:30:02

标签: java android layout relativelayout

我有下面的代码,问题是所有膨胀的视图都具有相同的ID(在player_item.xml中设置) - 因此当我旋转屏幕时,所有这些视图都以相同的值恢复。最简单的解决方案是删除那些id并让android自动生成它们但我不能这样做,因为我需要它们在相对布局中定位。任何想法如何解决这个问题?

player_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/player_name"
        style="@style/stats_edit_column"
        android:layout_width="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/goals"
        android:gravity="center_vertical" />

    <EditText
        android:id="@+id/goals"
        style="@style/stats_edit_column"
        android:layout_toLeftOf="@+id/assists"
        android:inputType="number"
        android:textSize="@dimen/text_size_normal" />

    <EditText
        android:id="@+id/assists"
        style="@style/stats_edit_column"
        android:layout_alignParentRight="true"
        android:inputType="number"
        android:textSize="@dimen/text_size_normal" />

</RelativeLayout>

for (PlayerStats playerStats : allPlayers) {
    View playerStatsView = getLayoutInflater().inflate(R.layout.player_item, null);

    TextView playerName = (TextView) playerStatsView.findViewById(R.id.player_name);
    playerName.setText(playerStats.getPlayerName());

    EditText goalsEditText = (EditText) playerStatsView.findViewById(R.id.goals);
    goalsEditText.setText(String.valueOf(playerStats.getGoals()));

    EditText assistsEditText = (EditText) playerStatsView.findViewById(R.id.assists);
    assistsEditText.setText(String.valueOf(playerStats.getAssists()));

    editLayout.addView(playerStatsView);
}

2 个答案:

答案 0 :(得分:0)

我建议为每个表单创建一个bean,并在移动到其他活动时将所有表单值设置为bean并将bean引用存储到共享首选项中,所以当你回到同一个活动时,只需重新加载所有值从bean中获取,这有助于保存表单的状态

我希望它有所帮助

答案 1 :(得分:0)

如何在标签中保留对playerStats的引用?

for (PlayerStats playerStats : allPlayers) {
    View playerStatsView = getLayoutInflater().inflate(R.layout.player_item, null);

    TextView playerName = (TextView) playerStatsView.findViewById(R.id.player_name);
    playerName.setText(playerStats.getPlayerName());

    EditText goalsEditText = (EditText) playerStatsView.findViewById(R.id.goals);
    goalsEditText.setText(String.valueOf(playerStats.getGoals()));

    EditText assistsEditText = (EditText) playerStatsView.findViewById(R.id.assists);
    assistsEditText.setText(String.valueOf(playerStats.getAssists()));

    playerStatsView.setTag(playerStats);

    editLayout.addView(playerStatsView);

}

getViewForPlayerStatsByTag(PlayerStats playerStats){
    for (int i=0;i<editLayout.getChildCount();i++){
        view = (View)editLayout.getChildAt(i);
        if (view.getTag()==playerStats){return view;}
    }
    return null;
}

getViewForPlayerStatsByTag将返回这些统计数据的player_item视图组,如果不存在,则返回null。