我是android新手,我正在尝试按照Android网站上的教程https://developer.android.com/training/implementing-navigation/nav-drawer.html制作导航抽屉。
在本教程中,他们使用ListView初始化变量,并在另一个类中使用该变量。他们是如何实现这一目标的?谢谢你的帮助
代码来自链接:
public class MainActivity extends Activity {
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
...
}
}
抽屉听众
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
我的代码:
主要活动在这里:
public class MainActivity extends Activity {
private String[] arrayPlanets;
private DrawerLayout mDrawerLayout;
public ListView mDrawerPlanetList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayPlanets = getResources().getStringArray(R.array.planets);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerPlanetList = (ListView) findViewById(R.id.list_planets);
mDrawerPlanetList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayPlanets));
mDrawerPlanetList.setOnItemClickListener(new DrawerItemClickListener());
}
抽屉听众在这里:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
private void selectItem(int position){
mDrawerPlanetList.setItemChecked(position, true);
aetTitle(arrayPlanets[position]);
mDrawerLayout.closeDrawer(mDrawerPlanetList);
}
@Override
public void setTitle(CharSequence title){
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
答案 0 :(得分:0)
您可以将listview设为public,并在包含该列表视图的mainActivity打开的另一个类上访问它。对于片段:((MainActivity)getActivity()).myListView