Fragment returning null from intent

2019-09-06 03:23发布

问题:

So i made a bunch of 4 buttons , put an intent to each of them . They all navigate to the same Fragment class . But their extras are different, so if button1 was clicked , Fragment would open and do a certain action , if button2 was clicked , Fragment would do another action and so on. I tried the code on normal activities and it worked , but in fragments its not working . It just returns me "Id is null"

Class sending the intent

public class Intennt extends ActionBarActivity {

Button bt1,bt2,bt3,bt4;
Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_intennt);
    bt1 = (Button) findViewById(R.id.button);
    bt2 = (Button) findViewById(R.id.button2);
    bt3 = (Button) findViewById(R.id.button3);
    bt4 = (Button) findViewById(R.id.button4);


    bt1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, ItemListActivity.class);

i.putExtra(ItemDetailFragment.ID_ACTION,ItemDetailFragment.ACTION_1);
            startActivity(i);
        }
    });

    bt2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, ItemListActivity.class);  
            i.putExtra(ItemDetailFragment.ID_ACTION, 
  ItemDetailFragment.ACTION_2);
            startActivity(i);
        }
    });
}

Fragment receiving the intent and extras

public class ItemDetailFragment extends Fragment {
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_3 = 3;
public static final int ACTION_4 = 4;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";


public static final String ARG_ITEM_ID = "item_id";


private DummyContent.DummyItem mItem;

public ItemDetailFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    if (getArguments().containsKey(ARG_ITEM_ID)) {
        // Load the dummy content specified by the fragment
        // arguments. In a real-world scenario, use a Loader
        // to load content from a content provider.
        mItem = 
DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
    }


    int id = getActivity().getIntent().getIntExtra(ID_ACTION, -1);

    if (id == ACTION_NULL) {
        Log.d("TAG", "id is null");
        Toast.makeText(getActivity(), "id is null!", 
Toast.LENGTH_SHORT).show();
    } else if (id == ACTION_1) {
        Log.i("TAG", "ALLOHA! from button 1");
        Toast.makeText(getActivity(), "Aloha from button 1!", 
Toast.LENGTH_LONG).show();
    } else if (id == ACTION_2) {
        Log.i("TAG", "Hello from button 2");
        Toast.makeText(getActivity(),"Hello from button 2!", 
Toast.LENGTH_LONG).show();
    }
    else if (id == ACTION_3) {
        Log.i("TAG", "Hello from button 3");
        Toast.makeText(getActivity(),"Hello from button 2!", 
Toast.LENGTH_LONG).show();
    }
    else if (id == ACTION_4) {
        Log.i("TAG", "Hello from button 4");
        Toast.makeText(getActivity(),"Hello from button 2!", 
Toast.LENGTH_LONG).show();
    }


}

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



    return rootView;
}
}

回答1:

To navigate to a fragment, you need to instantiate the fragment class then use the FragmentManager to proceed to a transaction :

FragmentClass fragment = new FragmentClass();

getFragmentManager()    
    .beginTransaction()
    .replace(R.id.your_fragment_view, fragment)
    .commit();

You can proceed to every action right in the current activity (as it stays the main activity).



回答2:

public class Questions extends DialogFragment {

private static Button Submit;
public int count = 0;

public interface DialogListener {
    void onQuestionsFinish(ArrayList<xmlQuestion> l);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
    getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
    //getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);



    Submit = (Button) rootView.findViewById(R.id.SubmitButton);


    Submit.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0){
            for(int i = 0; i<questionList.size(); i++)
            {
                questionList.get(i).setAnswer();
            }
            DialogListener activity = (DialogListener) getActivity();
            activity.onQuestionsFinish(questionList);
            Questions.this.dismiss();
        }
    });

    DisplayMetrics metrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    yInch = metrics.ydpi;
    pixHeight = metrics.heightPixels;

    Display display = getActivity().getWindowManager().getDefaultDisplay();
    Point size = new Point(); display.getSize(size);
    screenWidth=size.x; screenHeight=size.y;

    LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,screenHeight*900/1024);
    BodyLayout.setLayoutParams(bodyParams);

    WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
    wmlp.height=screenHeight; wmlp.width=screenWidth;

    getDialog().getWindow().setAttributes(wmlp);
    WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
    lp.dimAmount=0.4f;
    getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    getDialog().setCanceledOnTouchOutside(true);


    return rootView;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_FRAME, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);

}


public Questions()
{

}

}

You don't have to use intents to start fragments. My main benefit for using fragments is being able to reference the data in each one much easier. You can simply create a new instance of your fragment class, and assign it's public variables. Then start it like so...

Questions q = new Questions();
q.count = 0;
q.show(getSupportFragmentManager(), "Dialog Fragment");