안드로이드 공부 중 툴바 관련 질문입니다.

조회수 3337회

프로젝트를 처음 만들때 설정하는 내비게이션 드로어로 메뉴들을 만들어 주고 그 메뉴중 두번째 메뉴를 누르면 웹뷰를 바로 띄우고 싶습니다. 인텐트로 웹뷰를 띄우긴 했지만, 기존에 설정된 툴바가 없어져 새로 띄워진 웹뷰에서는 내비게이션 드로어를 사용할 수 없게 됩니다.

이미지

이미지

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);





    MainFragment fragment = new MainFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction =    getSupportFragmentManager().beginTransaction();

    fragmentTransaction.replace(R.id.fragment_container, fragment); 
    fragmentTransaction.commit();


    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });


    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();


    navigationView = (NavigationView) findViewById(R.id.nav_view); 
    //How to change elements in the header programatically
    View headerView = navigationView.getHeaderView(0);
    TextView emailText = (TextView) headerView.findViewById(R.id.email);
    emailText.setText("ghkvud5638@naver.com");

    navigationView.setNavigationItemSelectedListener(this); 


}


public void onButton1Clicked(View v){
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.naver.com"));
    startActivity(intent);

}

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


@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();

    if (id == R.id.action_settings) {
        return true;
    } else if(id ==R.id.action_search){

        return true;
    }

    return super.onOptionsItemSelected(item);
}



@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.sideMenu1) {
        //Set the fragment initially
        MainFragment fragment = new MainFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    }        else if (id == R.id.sideMenu2) {

         Intent intent = new Intent(getApplication(), webViewActivity.class);
         startActivity(intent);


    } else if (id == R.id.sideMenu3) {

        Menu3Fragment fragment = new Menu3Fragment();   
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();



    } else if (id == R.id.sideMenu4) {

    } else if (id == R.id.sideMenu5) {

    } else if (id == R.id.sideMenu6) {

    }

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

}

}

activity_web_view.xml

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView1"
    ></WebView>

webViewActivity.java

public class webViewActivity extends AppCompatActivity {

WebView webView1;
Toolbar toolbar;

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




    webView1 = (WebView) findViewById(R.id.webView1);
    WebSettings webSettings = webView1.getSettings();

    webSettings.setJavaScriptEnabled(true);

    webView1.loadUrl("http://m.naver.com");






}

}

  • (•́ ✖ •̀)
    알 수 없는 사용자

2 답변

  • 새로운 액티비티를 실행하면 기존 액티비티 화면을 덮는다.라고 접근하면 이해가 쉽지 않을까 싶습니다. 올려주신 코드에서 메인 액티비티에는 네비게이션 드로어가 있지만 웹뷰 액티비티에는 네비게이션 드로어가 존재하지 않습니다. 즉, 네비게이션 드로어가 있는 메인 액티비티에서 네비게이션 드로어가 없는 웹뷰 액티비티를 실행했기 때문에 발생하는 현상입니다. 좀 더 자세한 내용은 작업 및 백 스택 문서를 읽어보시기 바랍니다.

    만일 메인 액티비티의 툴바(그리고 네비게이션 드로어)는 그대로 둔 채 툴바 아래의 영역만 웹뷰로 보여주고 싶다면 프래그먼트를 사용하시기 바랍니다. 동작하는 수준의 간단한 샘플 코드를 첨부했으니 참고하세요.

    기존 웹뷰 액티비티 실행하는 곳을 아래 코드로 변경

    getSupportFragmentManager().beginTransaction()
        .add(R.id.fragment_container, WebViewFragment.newInstance("http://www.naver.com"))
        .addToBackStack(null)
        .commit();
    

    WebViewFragment.java 추가

    public class WebViewFragment extends Fragment {
    
        private static final String URL = "url";
    
        public static Fragment newInstance(String url) {
            Fragment fragment = new WebViewFragment();
            Bundle args = new Bundle();
            args.putString(URL, url);
            fragment.setArguments(args);
            return fragment;
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            WebView webView = new WebView(getActivity());
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl(getArguments().getString(URL));
            webView.setWebChromeClient(new WebChromeClient());
            webView.setWebViewClient(new WebViewClient());
            return webView;
        }
    }
    
    • (•́ ✖ •̀)
      알 수 없는 사용자
  • 친절한 답변 감사합니다! 하지만 말씀하신대로 MainActivity.java 의 Intent intent = new Intent(getApplication(), webViewActivity.class); startActivity(intent); 부분을 getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, WebViewFragment.newInstance("http://www.naver.com")) .addToBackStack(null) .commit();

    로 바꾸고, WebViewFragment.java 를 새로 추가 해도 웹뷰는 뜨지만 툴바가 아예 사라지는 현상이 발생하네요 .(제가 업로드 해드린 웹뷰가 띄워진 화면의 사진에서는 툴바가 있긴 있었지만 기존의 툴바와는 다르게 내비게이션 드로어를 쓸 수 없는 툴바였습니다.. ) 초보라 못알아 들은 걸 수도있어서,, 자세한 답변 부탁드립니다 ㅠㅠ 감사합니다

    • (•́ ✖ •̀)
      알 수 없는 사용자
    • activity_main.xml 파일 내에서 fragment_container 레이아웃이 어떻게 배치되어 있는지 확인해보세요. fragment_container 내부에 툴바가 있다면 툴바가 보이지 않게 됩니다. LinearLayout 또는 RelativeLayout을 이용해서 툴바 아래쪽으로 fragment_container가 위치하도록(=수직 방향으로 배치) 레이아웃을 수정하시기 바랍니다. 알 수 없는 사용자 2016.7.6 13:51

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)