将相同活动的包发送到它的片段

时间:2016-06-23 13:01:22

标签: android android-fragments

我试图在Android中编写我的第一个大项目,这也是我第一次真正在这里写作。我一直试图让这个问题一整天都无效,如果有人能告诉我哪里错了,我会非常感激。我知道从活动中获取Fragment字段是不好的做法,但这是我在Fragment TextViews中没有收到null的唯一方法。否则TextViews为null。我尝试在不同的片段生命周期事件(onAttach和onCreate)中处理捆绑包,但没有任何帮助,他们仍然没有看到捆绑包中的值。非常感谢提前! 还有一个问题,我是否理解,如果我想将一个活动包发送到其他活动片段,唯一的方法是将其发送到另一个活动,然后重新发送到片段或创建一个接口?也许有一些我不知道的直接方式?非常感谢提前!

这是我的片段:

public class MatchFragment extends Fragment {
    User clickedUser=new User("","","","","",0.0,0.0,0.0,0.0,false,false);

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root;
        root=inflater.inflate(R.layout.fragment_match,container,false);
        Intent intent = getActivity().getIntent();
        Bundle bundle = this.getArguments();
        if(bundle!=null)
            clickedUser = bundle.getParcelable("clickedUser");
        else
            Toast.makeText(getActivity(),getString(R.string.noMatches),Toast.LENGTH_SHORT).show();

        TextView nickNameTv=(TextView)root.findViewById(R.id.matchName);
        TextView firstLastNameTv=(TextView)root.findViewById(R.id.firstLastName);
        TextView paymentRequiredTv=(TextView)root.findViewById(R.id.paymentRequired);//if payment required - red "payment required", else green "can help for free"
        Button mail=(Button)root.findViewById(R.id.mailBtn);
        Button call=(Button)root.findViewById(R.id.callBtn);
        Button sms=(Button)root.findViewById(R.id.smsBtn);

        nickNameTv.setText(clickedUser.nickname);
        firstLastNameTv.setText(clickedUser.firstName+" "+clickedUser.lastName);
        boolean payment=clickedUser.paymentRequired;
        if(payment==true)
        {
            paymentRequiredTv.setText(getText(R.string.payable));
            paymentRequiredTv.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
        else
        {
            paymentRequiredTv.setText(getText(R.string.free));
            paymentRequiredTv.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
        }
        mail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mailIntent = new Intent(Intent.ACTION_SEND);
                mailIntent.setType("message/rfc822");
                mailIntent.putExtra(Intent.EXTRA_EMAIL, clickedUser.usermail);
                mailIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.mailMessage));
               // Intent mailer = Intent.createChooser(mailIntent, null);
                startActivity(mailIntent);

            }
        });
        call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri number = Uri.parse("tel:"+clickedUser.phonenumber);
                Intent callIntent = new Intent(Intent.ACTION_DIAL, number);
                startActivity(callIntent);

            }
        });
        sms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                smsIntent.setType("vnd.android-dir/mms-sms");
                smsIntent.setData(Uri.parse("sms:"+ clickedUser.phonenumber));
                startActivity(smsIntent);
            }
        });

        return root;
    }

}

及其XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:background="@android:color/white">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="LargeText"
        android:textColor="@color/colorPrimaryDark"
        android:id="@+id/matchName"
        android:layout_marginTop="44dp"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/paymentRequired" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@color/colorPrimaryDark"
        android:text="Large Text"
        android:id="@+id/firstLastName"
        android:layout_below="@+id/profilePicture"
        android:layout_alignEnd="@+id/paymentRequired" />

    <Button
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="@drawable/orange_blue_ripple_template"
        android:text="@string/call"
        android:id="@+id/callBtn"
        android:textColor="@android:color/white"
        android:layout_alignTop="@+id/smsBtn"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="@drawable/orange_blue_ripple_template"
        android:text="@string/mail"
        android:layout_marginStart="36dp"
        android:textColor="@android:color/white"
        android:id="@+id/mailBtn"
        android:layout_alignTop="@+id/callBtn"
        android:layout_toEndOf="@+id/callBtn" />

    <Button
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="@drawable/orange_blue_ripple_template"
        android:textColor="@android:color/white"
        android:text="@string/sms"
        android:id="@+id/smsBtn"
        android:layout_below="@+id/paymentRequired"
        android:layout_alignStart="@+id/paymentRequired"
        android:layout_marginTop="24dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/profilePicture"
        android:layout_below="@+id/matchName"
        android:layout_toStartOf="@+id/button2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/paymentRequired"
        android:layout_below="@+id/firstLastName"
        android:layout_toStartOf="@+id/callBtn" />


</RelativeLayout>

Here is the ACTIVITY: 

public class OneMatchActivity extends ToolbarActivity {

    User clickedUser=new User("","","","","",0.0,0.0,0.0,0.0,false,false);




     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_one_match);
            Bundle bundle=getIntent().getExtras();
            clickedUser=bundle.getParcelable("clickedUser");
            MatchFragment matchFragment = new MatchFragment();// or maybe ?? (MatchFragment)(getSupportFragmentManager().findFragmentById(R.id.fragment));
        Bundle bundleToFr = new Bundle();
        bundleToFr.putParcelable("clickedUser", clickedUser);
        matchFragment.setArguments(bundle);

和ACTIVITY的XML:

    <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/colorPrimary"
    tools:context="hyperactive.co.il.helppool.OneMatchActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="hyperactive.co.il.helppool.MatchFragment"
        android:id="@+id/fragment"
        android:layout_alignParentTop="true"
        android:layout_gravity="center_horizontal"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView2"
        android:background="@drawable/helpinghands"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:paddingTop="50dp"
        android:paddingBottom="50dp"
        android:layout_gravity="center_horizontal"
        />
</LinearLayout>

3 个答案:

答案 0 :(得分:0)

不是将Bundle中的参数从Activity传递到Fragment,而是通过实例化片段的静态工厂方法将参数传递给Fragment

 MyFragment myF = My fragment.newInstance(arg1,arg2);
 fragmentManager.replace(myF);
 ...

答案 1 :(得分:0)

 MyFragment myF =  MyFragment.getInstance(arg1,arg2);
 fragmentManager.add(myF);


public class MatchFragment extends Fragment{

 public static MatchFragment getInstance(String a, String b){
   MyFragment myF = new MyFragment();
    Bundle bundle = new Bundle();
    bundle.putString("a", a);
    bundle.putString("b", b);
   myF.setArguments(bundle);
   return myF
 }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle b = getArguments();
    if (b != null) {
    b.getString("a");
    b.getString("b");
  }
 }
}

答案 2 :(得分:0)

//Activity:

            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction trans = fm.beginTransaction();
            trans.replace(R.id.container, MyFragment.newInstance(arg1, arg2), "tag");
            trans.addToBackStack(null).commit();



//Fragment:

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

    public static MyFragment newInstance(String arg1, String arg2)
    {
        MyFragment frag = new MyFragment();
        Bundle args = new Bundle();
        args.putString("ARG1", arg1);
        args.putString("ARG2", arg2);
        frag.setArguments(args);
        return frag;
    }

    @Override public void onViewCreated(View view, Bundle savedInstanceState) {

        Bundle args = getArguments();
        if(args!=null)
        {

            String arg1 = args.getString("ARG1");
            String arg2 = args.getString("ARG2");

        }

    }

//Xml

//You can use .add instead .replace method. And in the xml layout you need //to change:    
 <fragment
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="hyperactive.co.il.helppool.MatchFragment"
        android:id="@+id/fragment"
        android:layout_alignParentTop="true"
        android:layout_gravity="center_horizontal"
        android:layout_centerHorizontal="true" />    ,  

//to this:

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center_horizontal"
        android:layout_centerHorizontal="true"/>