Android的碎片互动互动、碎片、Android

2023-09-07 15:23:20 作者:他夏了夏天

我有1活性的Andr​​oid应用程序2片段。 在第一个片段,我做了一个推杆按钮(btnA)。 关于第二个我推杆一个TextView(txtB)。

I have 1 activity with 2 fragments in a Android app. On the first fragment I did putt a button (btnA). On the second I putt a TextView (txtB).

如何通过按下按钮上的第一个活动设置在第二个片段的TextView的文本?

How can I set a Text in the TextView of the second fragment by pushing on the button on the first activity ?

THX,我是新来的Andr​​oid应用程序开发

Thx, I'm new to android app development

JoskXP

推荐答案

以下描述Android的最佳实践的这里。

Following Android best practice described here.

这是稍微比格雷姆的解决方案更详细,但让你的片段重复使用。 (你可以在另一个屏幕上使用FragmentWithButton,按钮可以做不同的事情)

This is slightly more verbose than the solution of Graeme, but allow reuse of your fragments. (You could use FragmentWithButton in another screen, and the button could do something different)

您有两个片段( FragmentWithButton 和 FragmentWithText )和一个活动( MyActivity

You have two Fragments (FragmentWithButton and FragmentWithText) and one activity (MyActivity)

创建一个接口 FragmentWithButtonHost FragmentWithButton

public class FragmentWithButton extends Fragment {

    FragmentWithButtonHost host;

    public interface FragmentWithButtonHost{
        public void onMyButtonClicked(View v);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            host = (FragmentWithButtonHost) activity;
        }
        catch (ClassCastException e) {
            // TODO Handle exception
        }
    }

    /**
     * Click handler for MyButton
     */
    public void onMyButtonClick(View v) {
        host.onMyButtonClicked(v);
    }
}

创建一个公开方法 FragmentWithText 设置从活动的文字:

Create a public method in FragmentWithText to set the text from the activity:

public class FragmentWithText extends Fragment{

      ...

      public void setText(String text) {
           // Set text displayed on the fragment
      }
}

请确保您的活动实现了 FragmentWithButtonHost 接口,并调用的setText 方法:

使用 Android 的碎片 Fragment 详情

Make sure your activity implements the FragmentWithButtonHost interface, and call the setText method:

public MyActivity implements FragmentWithButtonHost {

    ...

    @Override
    public void onMyButtonClicked(View v) {
        getFragmentWithText().setText("TEST");
    }

    public FragmentWithText getFragmentWithText() {
        // Helper method to get current instance of FragmentWithText, 
        // or create a new one if there isn't any
    }
}