2017-12-19 22 views
1

탐색 서랍 작업과 빈 조각을 만들었습니다. 내 액티비티가로드 될 때 중단 점을 쳤을 때 나는 내비게이션 드로어 활동의 메서드를 onCreate 메서드 내부에서 호출하고 있습니다. 그러나 메시지는 유감스럽게도 오류가 발생했습니다.activity에서 fragment를 호출하는 방법 onCreate 메서드

코드 : indexactivity

package com.example.sandeep.myapplication; 

import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.view.View; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuItem; 

public class IndexActivity extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_index); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     Fragment fragment = null; 
     Class fragementClass = null; 
     fragementClass = IndexFragement.class; 
     try{ 
      fragment = (Fragment)fragementClass.newInstance(); 
     } 
     catch (Exception e){ 
      e.printStackTrace(); 
     } 
     FragmentManager manager = getSupportFragmentManager(); 
     manager.beginTransaction().replace(R.id.flContent,fragment).commit(); 
     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.addDrawerListener(toggle); 
     toggle.syncState(); 

     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 
    } 

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

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

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

     if (id == R.id.nav_camera) { 
      // Handle the camera action 
     } else if (id == R.id.nav_gallery) { 

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

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

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

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

     } 

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

fragmentactivity :

package com.example.sandeep.myapplication; 

import android.content.Context; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 


public class IndexFragement extends Fragment { 
    // TODO: Rename parameter arguments, choose names that match 
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
    private static final String ARG_PARAM1 = "param1"; 
    private static final String ARG_PARAM2 = "param2"; 

    // TODO: Rename and change types of parameters 
    private String mParam1; 
    private String mParam2; 

    private OnFragmentInteractionListener mListener; 

    public IndexFragement() { 
     // Required empty public constructor 
    } 

    /** 
    * Use this factory method to create a new instance of 
    * this fragment using the provided parameters. 
    * 
    * @param param1 Parameter 1. 
    * @param param2 Parameter 2. 
    * @return A new instance of fragment IndexFragement. 
    */ 
    // TODO: Rename and change types and number of parameters 
    public static IndexFragement newInstance(String param1, String param2) { 
     IndexFragement fragment = new IndexFragement(); 
     Bundle args = new Bundle(); 
     args.putString(ARG_PARAM1, param1); 
     args.putString(ARG_PARAM2, param2); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (getArguments() != null) { 
      mParam1 = getArguments().getString(ARG_PARAM1); 
      mParam2 = getArguments().getString(ARG_PARAM2); 
     } 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     return inflater.inflate(R.layout.fragment_index_fragement, container, false); 
    } 

    // TODO: Rename method, update argument and hook method into UI event 
    public void onButtonPressed(Uri uri) { 
     if (mListener != null) { 
      mListener.onFragmentInteraction(uri); 
     } 
    } 

    @Override 
    public void onAttach(Context context) { 
     super.onAttach(context); 
     if (context instanceof OnFragmentInteractionListener) { 
      mListener = (OnFragmentInteractionListener) context; 
     } else { 
      throw new RuntimeException(context.toString() 
        + " must implement OnFragmentInteractionListener"); 
     } 
    } 

    @Override 
    public void onDetach() { 
     super.onDetach(); 
     mListener = null; 
    } 

    /** 
    * This interface must be implemented by activities that contain this 
    * fragment to allow an interaction in this fragment to be communicated 
    * to the activity and potentially other fragments contained in that 
    * activity. 
    * <p> 
    * See the Android Training lesson <a href= 
    * "http://developer.android.com/training/basics/fragments/communicating.html" 
    * >Communicating with Other Fragments</a> for more information. 
    */ 
    public interface OnFragmentInteractionListener { 
     // TODO: Update argument type and name 
     void onFragmentInteraction(Uri uri); 
    } 
} 
+0

처럼 그 일을 시도? –

+0

코드 디버깅을 시도 했습니까? 어떤 오류가 발생하고 있습니까? – Zingerella

+0

@EsirKings 코드가 추가되었습니다 ..... –

답변

0

귀하가 활동에서 조각을 시작하기 위해이 같은 것을 필요할 것 :

public boolean onNavigationItemSelected(MenuItem item) { 
    // Handle navigation view item clicks here. 
    int id = item.getItemId(); 
    Fragment fragment = null; 
    Class fragmentClass = null; 
    if (id == R.id.nav_camera) { 
     fragmentClass = FragmentOne.class; 
    } else if (id == R.id.nav_gallery) { 
     fragmentClass = FragmentTwo.class; 
    } else if (id == R.id.nav_slideshow) { 
     fragmentClass = FragmentOne.class; 
    } else if (id == R.id.nav_manage) { 
     fragmentClass = FragmentTwo.class; 
    } else if (id == R.id.nav_share) { 
     fragmentClass = FragmentOne.class; 
    } else if (id == R.id.nav_send) { 
     fragmentClass = FragmentTwo.class; 
    } 
    try { 
     fragment = (Fragment) fragmentClass.newInstance(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); 

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

그것은하지 않는 것 이 방법을 사용하면 네비게이션 서랍에서 조각을 시작할 수 없습니다. 대신

FragmentManager manager = getSupportFragmentManager(); 
manager.beginTransaction().replace(R.id.flContent,fragment).commit(); 

내가 당신의 요구 사항을 이해하고 같이 fragment-

FragmentManager manager = getSupportFragmentManager(); 
manager.beginTransaction().add(R.id.flContent,fragment).commit(); 

를 추가하는 코드 줄을 사용하여 라인 - 이들의

+0

인데 원하는 것은 탐색 서랍 작업로드가 조각이 열리고 활동이 아닌 경우와 같습니다. 항목을 클릭하면 코드가 실행됩니다. –

+0

탐색 서랍을 밖으로 내밀 때 조각을로드하려고합니까? – Aaron

0

, 당신은 조각이 열리지 활동을 취득 할 수 있습니다. 희망이 당신이 원하는 결과를 얻을 도움이 될 것입니다.

+0

이 작동하지 않습니다 ..... –

+0

언제 응용 프로그램이 열리거나 다른 경우에 해당 부분을로드 하시겠습니까? –

0

당신이 적어도 당신이 조각을 인스턴스화하려고하는 방법에 대한 코드를 게시 할 수이

@Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_index); 
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
      setSupportActionBar(toolbar); 
      IndexFragement fragment = new IndexFragement(); 
      FragmentManager manager = getSupportFragmentManager(); 
      manager.beginTransaction().add(R.id.flContent,fragment).commit(); 
//...... 
+0

작동하지 않습니다 ...... –

+0

실제 오류는 무엇입니까, 당신은 logcat에 무엇이 오류가 있다고합니까? – Rainmaker