2

I am writing a checkbook Android app that displays a list of bank accounts inside of a Navigation Drawer. The main screen of the application displays the basic account information (name, balance, etc).

I was able to implement the onClick method so that when an account is selected the main screen is updated, but I would like to implement this in a way that the first item in the ListView is selected when the application opens.

In other words, when I start the application I should see checking account information, but all that I see at the moment are default 0s, because no Intent was passed to the Activity when it started. I have tried to programmatically select the first item in the onCreate method of the main activity, but that did not work.

EDIT

Here is my code for the onCreate of the main activity:

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

    final View rootView = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);

    mDrawerListView = (ListView) rootView.findViewById(R.id.listview_account);

    // Get the Cursor that will be used to load accounts
    Cursor accounts = dataSource.getAccounts();

    // Make adapter.
    mAccountAdapter = new AccountAdapter(getActivity(), accounts, 0);

    mDrawerListView.setAdapter(mAccountAdapter);
    mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
            HeaderViewListAdapter headerViewAdapter = (HeaderViewListAdapter) adapterView.getAdapter();
            AccountAdapter adapter = (AccountAdapter) headerViewAdapter.getWrappedAdapter();
            Cursor cursor = adapter.getCursor();
            if(cursor != null && cursor.moveToPosition(i)){
                // Adjust main page
            }
        }
    });

    return rootView;
}

I tried to programatically select the first item after calling the setUp method, but that did not work. Should this be handled in the main activity or the fragment?

Mycoola
  • 1,135
  • 1
  • 8
  • 29
AdamMc331
  • 16,492
  • 10
  • 71
  • 133

4 Answers4

3

Have you taken a look at the example Navigation Drawer? As a side note, when creating a new project in Android Studio, one of the templates you can work with is a Navigation Drawer based application. I suggest taking a look and familiarizing yourself with how it works.

Anyway, I'm assuming you're working with that example, where you have a MainActivity and as you select items in your NavigationDrawer, you're essentially replacing fragments within your MainActivity container. For example, you could do something like this (somewhat psuedo-code):

private ListView mNavigationList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // init your listview, etc.
    mNavigationList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            onNavigationItemSelected(position);
        }
    });

    // show the "first" fragment
    onNavigationItemSelected(0);
}

private void onNavigationItemSelected(int position) {
    FragmentManager manager = getFragmentManager();
    Fragment f;
    String tag;

    switch (position) {
    case 0:
        tag = YourFragment.TAG;
        f = manager.findFragmentByTag(tag);
        if (f == null) {
            f = YourFragment.newInstance();
        }
    // ...
    }

    FragmentTransaction t = manager.beginTransaction();
    t.replace(R.id.container, f, tag);
    t.addToBackStack(tag);
    t.commit();
}

Your main activity layout likely includes a FrameLayout and the DrawerLayout. As you select items from the ListView of your Drawer, onNavigationItemSelected is fired and the FrameLayout container is replaced with the Fragment of your choice. Per your question, when the app loads, the container is replaced with the "first" fragment.

Jon
  • 1,234
  • 2
  • 12
  • 30
  • Sorry to get back so late. I had previously designed this differently, so I had to take some time reworking it to include something like this, but it worked like a charm. – AdamMc331 Dec 10 '14 at 22:18
  • Also, thanks a bunch for the detailed explanation and even the resource. I was using the example navigation drawer, but handled the onNavigationItemSelected very differently. I was using an onClickListener for the listview inside the drawer, but switching to this was a lot nicer and acted quicker than what I was doing. – AdamMc331 Dec 11 '14 at 14:09
1
public class HomeActivity extends FragmentActivity {

FragmentContainerHandler fragObj = new FragmentContainerHandler(
        getSupportFragmentManager());

private DrawerLayout mdrawerlayout;
private ListView mListview;
private ImageView mActionbarButton;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private ActionBarDrawerToggle mActionbartogle;
private TextView mtimertextview, headerTV;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    mListview = (ListView) findViewById(R.id.left_drawer);

    //set here array adapter
    mAccountAdapter = new AccountAdapter(getActivity(), accounts, 0);

    mListview.setAdapter(mAccountAdapter);

    mdrawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    ActionBar obj = getActionBar();

    obj.setCustomView(R.layout.action_bar_custum);
    obj.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

    mActionbarButton = (ImageView) findViewById(R.id.actionbarButton);
    mActionbarButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mdrawerlayout.openDrawer(mListview);
            if (mdrawerlayout.isDrawerOpen(mListview)) {
                mdrawerlayout.closeDrawer(mListview);

            }
        }
    });
    mListview.setOnItemClickListener(new SelectItemFormListView());
    fragObj.replaceFragment(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    return super.onOptionsItemSelected(item);
}
public class SelectItemFormListView implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        mdrawerlayout.closeDrawer(mListview);

        if (position == 5) {

            startActivity(new Intent(HomeActivity.this, MainAcivity.class));

            finish();
        } else {
            fragObj.replaceFragment(position);
        }
    }
}

}

public class FragmentContainerHandler {
FragmentManager fragmntMgr;

public FragmentContainerHandler(FragmentManager fragmntMgr) {
    this.fragmntMgr = fragmntMgr;
}

public void replaceFragment(int position) {
    Fragment fragment = null;
    if (position == 0) {
        fragment = new FindPeoples(this);
    }
    if (position == 4) {
        fragment = new ProfileView();
    }
    if (position == 5) {
        fragment = new Notification();
    }
    if (position == 6) {
        fragment = new Private_Message();
    }

    android.support.v4.app.FragmentTransaction ft = fragmntMgr
            .beginTransaction();

    // ft.setCustomAnimations(R.anim.rightsidein,0);
    List<Fragment> list = fragmntMgr.getFragments();
    if (list != null) {
        for (Fragment element : list) {

            if (element != null) {
                ft.remove(element);
                fragmntMgr.popBackStack();
            }
        }
    }
    ft.replace(R.id.content_frame, fragment, "fragment");
    ft.commit();
}

}

public class FindPost extends android.support.v4.app.Fragment {
private View rootview;

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

    rootview = inflater.inflate(R.layout.activity_find_post, container,
            false);

    return rootview;
}

}

wadali
  • 2,221
  • 1
  • 20
  • 38
0

Create a class to hold data for your items. Create a boolean variable isSelected in your item class. Check for isSelected in your adapters getView. Get the first item in listview in onCreate, and set the isSelected variable to true on your first item.

MeetTitan
  • 3,383
  • 1
  • 13
  • 26
  • I'm still not sure I understand. If I set isSelected is true, what do I do in the `getView`? – AdamMc331 Dec 03 '14 at 21:48
  • Adjust your main page depending on any other variables you have defined. You could (hint, hint) use the class I suggested to hold all item specific variables and then use those to update your page accordingly. – MeetTitan Dec 03 '14 at 21:55
  • I will keep playing with this idea. I'm starting to think that I need to rework the design. What if a user had an account selected before they closed the app? What if the user doesn't *have* any accounts for me to select? I will let you know if I can get something like this to work out. – AdamMc331 Dec 04 '14 at 18:19
  • @McAdam331, Set `isSelected` to false upon initialization of your item class to avoid selections from previous runs of the app. If you persist these classes using serialization or something, use `transient` on it as well. If the user doesn't have an account don't set any items `isSelected` variable, and show a splash page or something. – MeetTitan Dec 04 '14 at 18:27
0

put this property on your listview (in xml code)

android:choiceMode="singleChoice"

and write this code on your oncreate function

arraylist.get(0).setSelected(true);

arrayAdapter.notifyDataSetChanged();

use the generic class for listview

public class ListData 
{
public String MenuTitle="";

public boolean Selected=false;
public String getMenuTitle() 
{
    return MenuTitle;
}
public void setMenuTitle(String menuTitle) 
{
    MenuTitle = menuTitle;
}
public boolean isSelected() 
{
    return Selected;
}
public void setSelected(boolean selected) 
{
    Selected = selected;
}
}
Elango
  • 412
  • 4
  • 24