将参数传递给XML布局中定义的片段

时间:2015-09-23 18:42:31

标签: android android-fragments appcompat-v7-r22.1

public class ActivityA extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
    }
}

activity_one.xml

<fragment
    android:id="@+id/fragment"
    class="com.emoontech.waternow.FragmentA"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

FragmentA

public class FragmentA extends Fragment{
    public static FragmentEditEvent newInstance(String param1, String param2) {
        FragmentEditEvent fragment = new FragmentEditEvent();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
}

//点击按钮上的另一个活动

Intent intent = new Intent(this, ActivityA.class);
intent.putString("param1","val1");
intent.putString("param2","val2");
startActivity(intent);

//如何将这两个值发送到FragmentA?

3 个答案:

答案 0 :(得分:3)

回答我在那里https://stackoverflow.com/a/32748751/3301009在活动之间共享数据是非常笼统的,也可以用于片段

答案 1 :(得分:2)

试试这个

        // From ActivityA
        // retrieve the content of the intent from the previous activity
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment); // set content view to layout

        String param1Text= getIntent().getStringExtra("param1");
        String param2Text = getIntent().getStringExtra("param2");

        // this will pass the parameter to the fragment
        Fragment frament = FragmentA.newInstance(param1Text, param2Text);
        // use the fragment for what you desire

    }

答案 2 :(得分:0)

发现它不可能直接将参数传递给faragment,但替代方法是使用片段管理器并在activity中执行findFragmentById()以获取片段并根据需要设置日期。

编辑: If I declare a fragment in an XML layout, how do I pass it a Bundle?