我有一个DrawerLayout用作导航标签。我已经设置了所有东西,但是现在我需要一个小按钮来打开它并关闭它(ActionBarToggle,或类似的东西)。如何尽可能简单地设置它? (我是一个相对初学者,所以我不能很好地处理这个问题)
它只需要是左上角的按钮(就像youtube app所具有的那样),可以打开和关闭抽屉。
编辑:我正在为抽屉添加我的代码:
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
/***/
public NavDrawerListAdapter navDrawerListAdapter;
Fragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
categoryItems = new ArrayList<CategoryItem>();
categoryItems.populate();
navDrawerListAdapter = new NavDrawerListAdapter(this, categoryItems);
mDrawerList.addHeaderView(listheader, null, false);
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
}
}
除此之外,还有一个简单的Adapter(NavDrawerListAdapter)和一个简单的JavaBean CategoryItem。还有一个小函数populate(),它只是在列表中添加了一些元素。所有这些都完美无缺。我现在需要的是左上角的切换按钮,用于打开和关闭导航抽屉。
答案 0 :(得分:2)
public class MainActivity extends ActionBarActivity{
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_widget);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close);
toggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(toggle);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return toggle != null && toggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if (toggle != null)
toggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (toggle != null)
toggle.onConfigurationChanged(newConfig);
}
}
<强>编辑:强> 别忘了在build.gradle中添加对支持库的引用:
compile 'com.android.support:support-v4:22.0.0'
compile 'com.android.support:appcompat-v7:22.0.0'
并导入所有内容:
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.content.res.Configuration;
并检查 styles.xml ,父主题应为:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">