android 如何优雅地给Activity和Fragement传入参数

传参给Fragment

public class MyFragment extends Fragment {

    private static final String ARGS_KEY = "ARGS_KEY";
    private int mKey = -1;

    public static MyFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt(ARGS_KEY, type);
        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.xxx, container, false);
        mKey = getArguments().getInt(ARGS_KEY);
        return root;
    }
}
usgage: MyFragment myFragment = MyFragment.newInstance(123);

传参给Activity

public class ActivityOne extends Activity
{
    private static final String VALUE1 = "value1_param";
    private static final String VALUE2 = "value2_param";

    public static void startMe( Context ctx, int val1, String val2 )
    {
        Intent intent = new Intent( ctx, ActivityOne.class );
        intent.putExtra( VALUE1, val1 );
        intent.putExtra( VALUE2, val2 );
        ctx.startActivity( intent );
    }

    private int _value1;
    private String _value2;

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

        Bundle extras = getIntent().getExtras();
        if ( extras != null )
        {
            _value1 = extras.getInt( VALUE1 );
            _value2 = extras.getString( VALUE2 );
        }
    }
}
usgage: ActivityOne.startMe( this, 123, "abc" );

你可能感兴趣的:(java,andriod)