programing

프래그먼트 내에서 활동을 시작하려면 어떻게해야합니까?

goodcopy 2021. 1. 18. 22:05
반응형

프래그먼트 내에서 활동을 시작하려면 어떻게해야합니까?


이 질문에 이미 답변이 있습니다.

FragmentActivity각각 자체 조각을 보유 하는 탭 세트가 있습니다. 를 통해 해당 프래그먼트 내에서 새 활동을 시작 onClickListener하고 startActivity(myIntent)메서드를 사용하려고하면 내 응용 프로그램이 닫힙니다.

잠시 둘러 본 후라는 메서드에 대한 참조를 한두 개 찾았 startActivityFromFragment지만 한 시간 정도 검색 한 후 사용 방법 또는 이것이 사용해야하는 것인지에 대한 설명이나 예를 찾을 수 없습니다. .

내가 묻는 것은 활동에서 새 활동을 시작하는 것과 조각에서 새 활동을 시작하는 것 사이에 차이가 있는지 여부입니다. 그렇다면 구현해야 할 것은 무엇입니까?


당신은 그것을해야합니다 getActivity().startActivity(myIntent)


나는 그것을했다, 아래 코드가 나를 위해 일하고있다 ....

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);

        Button newPage = (Button)v.findViewById(R.id.click);
        newPage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HomeActivity.class);
                startActivity(intent);
            }
        });
        return v;
    }

대상 활동이 Manifest.xml 파일에 등록되어 있는지 확인하십시오.

하지만 제 경우에는 모든 탭이 HomeActivity에 표시되지 않습니다. 이에 대한 해결책이 있습니까?


프래그먼트에서 활동을 시작하는 것과 활동의 차이점은 두 경우 모두 활동이어야하므로 컨텍스트를 얻는 방법입니다.

활동에서 : 컨텍스트는 현재 활동입니다 ( this).

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

조각에서 : 컨텍스트는 상위 활동 ( getActivity())입니다. 프래그먼트 자체는를 통해 활동을 시작할 수 있으며 활동 startActivity()에서 수행 할 필요는 없습니다.

Intent intent = new Intent(getActivity(), NewActivity.class);
startActivity(intent);

여러 활동에 나타나는 (사용자 정의) 메뉴 조각에서 SendFreeTextActivity를 시작하려면 다음과 같이합니다.

MenuFragment 클래스에서 :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_menu, container, false);

    final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
    sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Log.d(TAG, "sendFreeTextButton clicked");
            Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
            MenuFragment.this.startActivity(intent);
        }
    });
    ...

인 텐트를 시작하려면 프래그먼트가있는 활동의 기본 컨텍스트를 사용하십시오.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

현재 활동 fBaseCtx어디에 있습니까 BaseContext? 당신은 그것을 얻을 수 있습니다fBaseCtx = getBaseContext();

참조 URL : https://stackoverflow.com/questions/12074608/how-do-i-start-an-activity-from-within-a-fragment

반응형