2016-06-09 3 views
0

서랍에서 옵션을 선택하고 다른 표시로 변경하면 강조 표시가 변경되지 않습니다. 첫 번째로 선택한 옵션은 강조 표시된 채로 유지되고 두 번째 옵션은 강조 표시되지 않습니다. 나는 많은 블로그에서 대답을 찾고 있지만 나를 위해 일한 것을 찾지 못했습니다.탐색 서랍 강조 표시가 올바르게 작동하지 않습니다.

public class MainActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemClickListener{ 

    ListView listView; 
    List<RowItem> rowItems; 
    private int navId; 
    private static final String NAV_ITEM_ID = "navId"; 

    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    private GoogleApiClient client; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     if (null == savedInstanceState){ 
      navId = R.id.nav_home; 
     } else { 
      navId = savedInstanceState.getInt(NAV_ITEM_ID); 
     } 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 

     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 

     ImageView profilePic = (ImageView)findViewById(R.id.profileImageView); 


     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 
     navigationView.getMenu().findItem(navId).setChecked(true); 

     rowItems = new ArrayList<RowItem>(); 
     for (int i = 0; i < DownloadFromServer.titles.length; i++) { 
      RowItem item = new RowItem(DownloadFromServer.images[i], DownloadFromServer.titles[i], 
        DownloadFromServer.descriptions[i], DownloadFromServer.puntos[i], 
        DownloadFromServer.puntuacion[i]); 
      rowItems.add(item); 
     } 

     // Get ListView object from xml 
     listView = (ListView) findViewById(R.id.list); 

     // Define a new Adapter 
     // First parameter - Context 
     // Second parameter - Layout for the row 
     // Third - the Array of data 

     CustomListViewAdapter adapter = new CustomListViewAdapter(this, 
       R.layout.principal_list_item, rowItems) { 
     }; 


     // Assign adapter to ListView 
     listView.setAdapter(adapter); 

     // ListView Item Click Listener 
     listView.setOnItemClickListener(this); 

    } 

    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, 
          long id) { 

     Intent intent = new Intent(this, PopupListCard.class); 
     intent.putExtra("Title", DownloadFromServer.titles[position]); 
     intent.putExtra("Desc", DownloadFromServer.descriptions[position]); 
     intent.putExtra("Image",DownloadFromServer.images[position].toString()); 
     intent.putExtra("Puntuacion", String.valueOf(DownloadFromServer.puntuacion[position])); 
     intent.putExtra("Puntos", String.valueOf(DownloadFromServer.puntos[position])); 

     startActivity(intent); 

    } 

    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      finish(); 
      BaseActivity.hideProgressDialog(); 
     } 
    } 


    @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) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     return super.onOptionsItemSelected(item); 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     // Handle navigation view item clicks here. 

     navId = item.getItemId(); 

     if (navId == R.id.nav_home) { 
      // Handle the action 

     } else if (navId == R.id.nav_my_profile){ 

      Intent intent = new Intent(this, MyProfile.class); 
      startActivity(intent); 

     } else if (navId == R.id.nav_buy_puntos) { 

     } else if (navId == R.id.nav_settings){ 

     } else if (navId == R.id.nav_share) { 

     } else if (navId == R.id.nav_feedback) { 

      Intent intent = new Intent(this, FeedbackActivity.class); 
      startActivity(intent); 

     } else if (navId == R.id.nav_help) { 

     } else if (navId == R.id.nav_log_out){ 

      finish(); 
      BaseActivity.hideProgressDialog(); 

     } 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

    @Override 
    public void onStart() { 
     super.onStart(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client.connect(); 
     Action viewAction = Action.newAction(
       Action.TYPE_VIEW, // TODO: choose an action type. 
       "Main Page", // TODO: Define a title for the content shown. 
       // TODO: If you have web page content that matches this app activity's content, 
       // make sure this auto-generated web page URL is correct. 
       // Otherwise, set the URL to null. 
       Uri.parse("http://host/path"), 
       // TODO: Make sure this auto-generated app URL is correct. 
       Uri.parse("android-app://com.gummyfish.appuntes3/http/host/path") 
     ); 
     AppIndex.AppIndexApi.start(client, viewAction); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     Action viewAction = Action.newAction(
       Action.TYPE_VIEW, // TODO: choose an action type. 
       "Main Page", // TODO: Define a title for the content shown. 
       // TODO: If you have web page content that matches this app activity's content, 
       // make sure this auto-generated web page URL is correct. 
       // Otherwise, set the URL to null. 
       Uri.parse("http://host/path"), 
       // TODO: Make sure this auto-generated app URL is correct. 
       Uri.parse("android-app://com.gummyfish.appuntes3/http/host/path") 
     ); 
     AppIndex.AppIndexApi.end(client, viewAction); 
     client.disconnect(); 
    } 

    protected void onSaveInstanceState (final Bundle outState){ 
     super.onSaveInstanceState(outState); 
     outState.putInt(NAV_ITEM_ID, navId); 
    } 
} 
+0

당신이 할 수있는이'navigationView.getMenu()의 getItem은 (indexOfTheItem) .setChecked (사실은). ' – Vucko

답변

0
navigationView.setCheckedItem(id); 

이 방법 은 당신뿐만 아니라 performIdentifierAction을 확인해야 API 23.0.0

년에 도입되었다. 지정된 항목을 선택하고 연관된 항목을 실행해야합니다.

0

이 문제를 해결할 수있는 방법은 여러 가지가있을 수 있습니다.

먼저 navigationView을 공개합니다. 그런 다음 먼저 체크 표시를 모두 지우고 체크를 설정하십시오. navigationView.getMenu().findItem(navId).setChecked(true);

코드 변경 사항을 찾으십시오.

private NavigationView navigationView; 

@Override 
public boolean onNavigationItemSelected(MenuItem item) { 
    // Handle navigation view item clicks here. 

    navId = item.getItemId(); 
    clearChecked(); 
    navigationView.getMenu().findItem(navId).setChecked(true); 

    if (navId == R.id.nav_home) { 
     // Handle the action 

    } else if (navId == R.id.nav_my_profile){ 

     Intent intent = new Intent(this, MyProfile.class); 
     startActivity(intent); 

    } else if (navId == R.id.nav_buy_puntos) { 

    } else if (navId == R.id.nav_settings){ 

    } else if (navId == R.id.nav_share) { 

    } else if (navId == R.id.nav_feedback) { 

     Intent intent = new Intent(this, FeedbackActivity.class); 
     startActivity(intent); 

    } else if (navId == R.id.nav_help) { 

    } else if (navId == R.id.nav_log_out){ 

     finish(); 
     BaseActivity.hideProgressDialog(); 

    } 
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    drawer.closeDrawer(GravityCompat.START); 
    return true; 
} 

private void clearChecked() { 
     int size = navigationView.getMenu().size(); 
     for (int i = 0; i < size; i++) { 
      navigationView.getMenu().getItem(i).setChecked(false); 
     } 
    } 
+0

는 당신의 도움을 주셔서 감사합니다. 그러나 clearChecked()에서 오류가 발생하고 그 루트를 알아낼 수 없습니다. 이 메시지는 다음과 같습니다. '가상 메소드 호출 시도'android.view.Menu android.support.design.widget.NavigationView.getMenu() 'null 객체 참조' – Nkuutz

+0

그대로 다른 코드를 유지하십시오. 나는 u가 navigationView를 초기화하지 않는다고 생각한다. – keshav

+0

어떻게 초기화되지 않습니까? 서랍이 작동하는 데 사용되었지만 올바른 옵션을 강조 표시하지 않았습니다. 초기화되지 않았다면 어떻게 작동할까요? 왜냐하면 나는 코드의 일부분을 변경하지 않았기 때문에 ... – Nkuutz

관련 문제