2015-11-13 7 views
1

Мне нужно настроить свой навигационный ящик следующим образом.Невозможно настроить навигационный ящик

enter image description here

В настоящее время я был в состоянии добавить следующие части.

enter image description here

Независимо от того, насколько сильно я пытался добавить еще текстовые поля, редактировать тексты и изображения, я не мог этого сделать.

Вот мой пример кода.

Это, как я добавил поля в strings.xml

<string-array name="titles"> 
     <item>Hotel</item> 
     <item>Historical Sites</item> 
     <item>Shopping</item> 
     <item>Restaurant</item> 
     <item>Attractions</item> 
     <item>wild Life</item> 
     <item>Tour Service</item> 
    </string-array> 

    <array name="icons"> 
     <item>@drawable/ic_hotel</item> 
     <item>@drawable/ic_historical</item> 
     <item>@drawable/ic_shopping</item> 
     <item>@drawable/ic_resturant</item> 
     <item>@drawable/ic_attraction</item> 
     <item>@drawable/ic_wildlife</item> 
     <item>@drawable/ic_tourservices</item> 
    </array> 

Вот мой mainactivity.xml

<android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/drawer_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<!-- Framelayout to display Fragments --> 
<FrameLayout 
    android:id="@+id/frame_container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

</FrameLayout> 


<!-- Listview to display slider menu --> 
<include layout="@layout/drawer_layout" /> 

Вот мой list_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="48dp" 
    android:padding="5dp" > 

     <ImageView 
      android:id="@+id/icon" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentLeft="true" 
      android:layout_centerVertical="true" 
      android:layout_marginLeft="12dp" 
      android:layout_marginRight="12dp" 
      /> 

     <TextView 
      android:id="@+id/title" 
      android:layout_width="wrap_content" 
      android:layout_height="match_parent" 
      android:layout_marginTop="10dp" 
      android:layout_toRightOf="@id/icon" 
      android:gravity="center_vertical" 
      android:textColor="#ffffff" 
      android:textSize="20sp" /> 

     <CheckBox 
      android:id="@+id/checkBox" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentRight="true"/> 

</RelativeLayout> 

Вот мой CustomAdapter.java

public class CustomAdapter extends BaseAdapter { 
    Context context; List<RowItem> rowItem; 

    CustomAdapter(Context context, List<RowItem> rowItem) { 
     this.context = context; 
     this.rowItem = rowItem; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     if (convertView == null) { 
      LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); 
      convertView = mInflater.inflate(R.layout.list_item, null); 
     } 
     ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon); 
     TextView txtTitle = (TextView) convertView.findViewById(R.id.title); 
     RowItem row_pos = rowItem.get(position); 

     // setting the image resource and title 
     imgIcon.setImageResource(row_pos.getIcon()); 
     txtTitle.setText(row_pos.getTitle()); 
     return convertView; 
    } 

    @Override 
    public int getCount() { 
     return rowItem.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return rowItem.get(position); 
    } 

    @Override 
    public long getItemId(int position) { 
     return rowItem.indexOf(getItem(position)); 
    } 
} 

Вот мой mainactivity.java

public class Extract extends ActionBarActivity { 

    String[] menutitles; 
    TypedArray menuIcons; 

    // nav drawer title 
    private CharSequence mDrawerTitle; 
    private CharSequence mTitle; 
    private DrawerLayout mDrawerLayout; 
    private ListView mDrawerList; 
    private ActionBarDrawerToggle mDrawerToggle; 
    private List<RowItem> rowItems; 
    private CustomAdapter adapter; 



    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_extract); 

     mTitle = mDrawerTitle = getTitle(); 
     menutitles = getResources().getStringArray(R.array.titles); 
     menuIcons = getResources().obtainTypedArray(R.array.icons); 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerList = (ListView) findViewById(R.id.slider_list); 



     rowItems = new ArrayList<RowItem>(); 

     for (int i = 0; i < menutitles.length; i++) { 
      RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(  i, -1)); 
      rowItems.add(items); 
     } 

     menuIcons.recycle(); 
     adapter = new CustomAdapter(getApplicationContext(), rowItems); 
     mDrawerList.setAdapter(adapter); 
     mDrawerList.setOnItemClickListener(new SlideitemListener()); 

     // enabling action bar app icon and behaving it as toggle button 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setHomeButtonEnabled(true); 

     mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name) 
     { 
      public void onDrawerClosed(View view) { 
       getSupportActionBar().setTitle(mTitle); 
       // calling onPrepareOptionsMenu() to show action bar icons 
       invalidateOptionsMenu(); 
      } 
      public void onDrawerOpened(View drawerView) { 
       getSupportActionBar().setTitle(mDrawerTitle); 
       // calling onPrepareOptionsMenu() to hide action bar icons 
       invalidateOptionsMenu();   } 
     }; 

     mDrawerLayout.setDrawerListener(mDrawerToggle); 
     if (savedInstanceState == null) { 
      // on first time display view for first nav item 
      updateDisplay(0); 
     } 
    } 

    class SlideitemListener implements ListView.OnItemClickListener { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      updateDisplay(position); 
     } 
    } 
     private void updateDisplay(int position) { 
      Fragment fragment = null; 
      switch (position) { 
       case 0: 
        fragment = new MapFragment(); 
        break; 

       case 1: 
        fragment = new hotel(); 
        break; 

       case 2: 
        fragment = new restaurant(); 
        break; 


       default: 
        break; 
      } 
      if (fragment != null) { 
       FragmentManager fragmentManager = getFragmentManager(); 
       fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit(); 

       // update selected item and title, then close the drawer 
       setTitle(menutitles[position]); 
       mDrawerLayout.closeDrawer(mDrawerList); 
      } 
      else { 
       // error in creating fragment 
       Log.e("Extract", "Error in creating fragment"); 
      } 
     } 

    @Override 
    public void setTitle(CharSequence title) { 
     mTitle = title; 
     getSupportActionBar().setTitle(mTitle); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_extract, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // toggle nav drawer on selecting action bar app icon/title 
     if (mDrawerToggle.onOptionsItemSelected(item)) { 
      return true; 
     } 
     // Handle action bar actions click 
     switch (item.getItemId()) { 
     case R.id.action_settings: 
      return true; 
      default : 
       return super.onOptionsItemSelected(item); 
     } 
    } 

    /*** * Called when invalidateOptionsMenu() is triggered */ 
    @Override 
    public boolean onPrepareOptionsMenu(Menu menu) { 
     // if nav drawer is opened, hide the action items 
     boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
     menu.findItem(R.id.action_settings).setVisible(!drawerOpen); 
     return super.onPrepareOptionsMenu(menu); 
    } 

    /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ 
    @Override 
    protected void onPostCreate(Bundle savedInstanceState) { 
     super.onPostCreate(savedInstanceState); 
     // Sync the toggle state after onRestoreInstanceState has occurred. 
     mDrawerToggle.syncState(); } 


    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 
     // Pass any configuration change to the drawer toggles 
     mDrawerToggle.onConfigurationChanged(newConfig); 
    } 
} 

Вот мой drawer_layoout.xml

<?xml version="1.0" encoding="utf-8"?> 
<DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <ListView 
     android:id="@+id/slider_list" 
     android:layout_width="300dp" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:background="#000000" 
     android:choiceMode="singleChoice" 
     android:divider="@android:color/transparent" 
     android:dividerHeight="0dp" 
     android:layout_weight="1" /> 

</DrawerLayout> 

Пожалуйста, помогите мне, чтобы добавить изображение, два текстовых вид вблизи изображения, горизонтальная линия , и текст редактирования. Заранее спасибо

ответ

0

В вашем MainActivity, добавить новое поле для LinearLayout, и присвоить ей значение в onCreate()

private LinearLayout mLenear; 

mLenear = (LinearLayout)findViewById(R.id.left_drawer);// inside onCreate 

Затем добавьте следующий код в onPrepareOptionsMenu

@Override 
public boolean onPrepareOptionsMenu(Menu menu) { 
    // if nav drawer is opened, hide the action items 
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear); 
    menu.findItem(R.id.action_settings).setVisible(!drawerOpen); 
    return super.onPrepareOptionsMenu(menu); 
} 

Затем измените ваш closeDrawer как это.

mDrawerLayout.closeDrawer(mLenear); 

Это должно решить вашу проблему.:)

+0

Это решило мою проблему. Спасибо Manu –

+0

счастлив помочь :) –

0

это будет основной макет, который вы будете использовать его из двух частей одна основная часть, которая будет иметь компоновку главного экрана и drawer_layout это макет, который имеет вы навигацию раскладки просмотра

Таким образом, вы должны будешь создать drawer_layout, как вы хотите, чтобы отобразить и просто назвать его здесь

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/navigationDrawer" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <FrameLayout 
     android:id="@+id/mainLayout" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"> 

     // you will have layout that you will use for your main activity or the activity where you are showing your navigation View 


    </FrameLayout> 

    // the drawer_layout will define your navigation View 
    <include layout="@layout/drawer_layout" /> 

</android.support.v4.widget.DrawerLayout> 

в своей деятельности вы получите доступ к вашему drawer_layout и получить доступ к своему виду, используя этот объект как

DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.navigationDrawer); 
// Example of getting your view object 
ImageView yourImageView = (ImageView) drawerLayout.findViewById(R.id.imageView); 
// you can access any your drawerView using that drawerLayout object 
+0

Я не совсем понимаю. Мне нужно все, что в навигационном ящике, например, мое изображение 1. –

+0

рассмотрите ваш drawer_layout как вид навигации и сделайте то, что вы хотите увидеть в навигации. Просмотр –

+0

Я создал файл ресурсов XML с именем drawer_layout и добавил свой список в него, а затем вызвал но возникла ошибка времени выполнения, не удалось запустить активность ComponentInfo {com.myayubo/com.myayubo.Extract}: java.lang.ClassCastException: android.widget.LinearLayout $ LayoutParams не может быть брошен в android.support.v4.widget.DrawerLayout $ LayoutParams –

Смежные вопросы