我的android示例应用程序有问题。我有一个带有ListView菜单的NavigationView。我无法将选中的项目标记为选中。我尝试了setItemChecked但什么都没有:(
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DrawerLayout dl;
private ActionBarDrawerToggle t;
private NavigationView nv;
private ListView listview;
private List < String > markets;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dl = (DrawerLayout) findViewById(R.id.activity_main);
listview = (ListView) findViewById(R.id.listview);
t = new ActionBarDrawerToggle(this, dl, R.string.Open, R.string.Close);
dl.addDrawerListener(t);
t.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setElevation(0);
markets = new ArrayList < String > ();
markets.add("Sample");
ArrayAdapter < String > adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, markets);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
nv = (NavigationView) findViewById(R.id.nv);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (t.onOptionsItemSelected(item)) return true;
return super.onOptionsItemSelected(item);
}
@Override
public void onItemClick(AdapterView << ? > adapterView, View view, final int position, long l) {
Fragment fragment = null;
Class fragmentClass = null;
if (position == 0) fragmentClass = FirstFragment.class;
else fragmentClass = SecondFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
setTitle(adapterView.getItemAtPosition(position).toString());
dl.closeDrawers();
}
}