Android Master Detail Flow - Select first item in

2019-04-11 08:45发布

问题:

I created a new app relying on the default "Master Detail Flow" template, chosen in the "New Project..." dialog of Android Studio. Then I adapted the application to fit my needs and my data. Works like a charm on handhelds and tablets.

The only thing I want to achive ist to autoselect the first item in the list, showing the detail view and setting the list item as selected.

In the "ItemListFragment" I called the "onListItemClick(...)" method in the overwritten "onStart()" method. This had following behaviours:

  • When rotating the device, the first item in the list gets selected (not the previously selected one)
  • The list item does not get marked as selected in the list

Could someone point me in the right direction on how to achieve this. Because I only want this behaviour in "Tablet-Mode" I guess I have to put it into the ItemListActivity?

Thanks

EDIT: This is my "onCreate" method of the "ItemListActivity"

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_item_list);
    if (findViewById(R.id.item_detail_container) != null) {
        mTwoPane = true;
        ((ItemListFragment) getFragmentManager()
                .findFragmentById(R.id.item_list))
                .setActivateOnItemClick(true);
    }
}

回答1:

You could resolve this by removing the onListItemClick(...) call in the onStart(...) of ItemListFragment and instead adding this below snippet to the end of setActivateOnItemClick(...):

    // If on dual-pane view, pre-select the first item from the chapter list
    if (activateOnItemClick && mActivatedPosition == ListView.INVALID_POSITION) {
        getListView().performItemClick(getListView(), 0, getListView().getItemIdAtPosition(0));
    }

Also, add this one line of code if it is not already there in onListItemClick(...) in ItemListFragment:

    mActivatedPosition = position;

Please check the diff on the file ChapterListFragment from these commits yesterday on my GH repo to get a little more context to my solution - https://github.com/floydpink/BhagavadGita/compare/047de35c39f01c6341a7f677aa5b7cc47a7144a3...b1b45d15cd68290e2ebe909ca920bd7aefd2805e#diff-1

Hope this helps