屏幕旋转后,在片段中恢复listview滚动位置

时间:2014-06-06 23:04:42

标签: android listview android-fragments android-listview

请相信我,我真的已经尝试过在网上找到的很多东西,包括thisthis和listview.onSaveInstanceState(),但都没有成功。 我将发布一些方法:

    public class ChatFragment extends Fragment implements OnItemClickListener,
    OnItemLongClickListener {

private String target;
private ListView listview;
private EditText edittext;
private Conversa conversa;
private MainActivity activity;

private int position_recover = -1;

public static final String LISTPOSITION = "listposition";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    setHasOptionsMenu(true);

    View view = inflater.inflate(R.layout.chat_layout, container, false);

    target = getArguments().getString(MyService.EXTRA_TARGET);

    // esse target é passado com o mTag no contrutor do tablistener.
    // no tablistener ele precisa ser igual definido na tab da activity, mas
    // daqui pra baixo eh target

    if (target.equalsIgnoreCase(MainActivity.TITLE_TAB_CHAT)) {
        target = MyService.CANAL;
    }

    activity = (MainActivity) getActivity();

    conversa = MyService.getConversa(target);

    listview = (ListView) view.findViewById(R.id.chatlist);

    edittext = (EditText) view.findViewById(R.id.chatinput);

    listview.setAdapter(conversa);
    listview.setOnItemClickListener(this);
    listview.setOnItemLongClickListener(this);

    // LISTENER QUE RECEBERA O "ENVIAR" DO TECLADO DO ANDROID
    edittext.setOnEditorActionListener(...);

    if (savedInstanceState != null) {

        position_recover = savedInstanceState.getInt(LISTPOSITION);

    }

    return view;
}

    @Override
public void onResume() {
    super.onResume();
    setHint();

    if (position_recover != -1) {
        listview.setSelection(position_recover);
        position_recover = -1;
    }

}

@Override
public void onSaveInstanceState(Bundle outState) {

    outState.putInt(LISTPOSITION, listview.getLastVisiblePosition());

    super.onSaveInstanceState(outState);
}

旋转后,如果listiview处于开始位置,它仍处于开始位置,否则它将结束。

请帮助我,因为我已经有一段时间了。

0 个答案:

没有答案