当我们导航并再次出现在同一片段时,如何保持ListView项处于选中状态



我有一个列表视图,它在Fragment中。我正在单击项目它保持选中状态,因为我在listselected.xml 中使用了以下代码

<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <solid android:color="#646973" />
    </shape>
    </item>
<item android:state_selected="true">
    <shape android:shape="rectangle">
        <solid android:color="#646973" />
    </shape></item>
<item android:state_activated="true">
    <shape android:shape="rectangle">
        <solid android:color="#646973" />
    </shape></item>
 <item android:state_accelerated="false">
     <shape android:shape="rectangle">
        <solid android:color="#646973" />
    </shape>
 </item>

但当我从一个片段转到另一个片段,当我再次访问同一个片段时,它会被删除,我想这样做。请帮帮我。当创建OnCreateView时,列表视图是动态填充的。

我以前也遇到过同样的问题。你可以这样保存你的碎片状态。将您的视图保存在片段中。

View myLayout=null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        return null;
    }
    if(myLayout==null){
        //initialize your layout here. 
         myLayout = inflater.inflate(R.layout.frag_layout, container, false);
    }
      else{
          try{
          ((ViewGroup)myLayout.getParent()).removeView(myLayout);
          }catch(Exception e){
              //an exception will be thrown when the very first time it trying to remove view from the parent
          }
     }
    return myLayout;
}

最新更新