【问题标题】:How to pass button clicks from a Fragment to Main Activity如何将按钮点击从片段传递到主活动
【发布时间】:2019-08-19 22:03:15
【问题描述】:

我正在尝试通过 MainActivity 访问我的 GetPhone 片段中名为 verify_otp 的按钮。

我尝试过使用 btnVerify = findViewById(R.id.verify_otp),但这会创建一个 NullPointerException。

我还使用了将按钮单击处理为 answered here 的界面,再次创建 NullPointerException。

我也尝试过使用这样的函数来返回我的按钮

public ImageButton getMyButton(){
return myButton;
}

在我的主要活动中调用它:

GetPhone getPhoneFragment = new GetPhone();
ImageButton btnVerify = getPhoneFragment.getMyButton();

这也会产生 NullPointerException。

这是我的 GetPhone 片段:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".GetPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#fff"
android:outlineProvider="bounds">

<RelativeLayout
    android:layout_width="48dp"
    android:layout_height="48dp">
    <Spinner
        android:id="@+id/country_spinner"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/spinner_left_curved"
        style="@style/Widget.AppCompat.Spinner"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:background="@drawable/icon_dropdown" />

</RelativeLayout>


   <androidx.appcompat.widget.AppCompatEditText
       android:id="@+id/phone_num"
       style="@style/Widget.AppCompat.EditText"
       android:background="@drawable/get_phone_center"
       android:paddingStart="16dp"
       android:paddingEnd="16dp"
       android:layout_weight="1"
       android:layout_width="0dp"
       android:layout_height="48dp"
       android:inputType="phone"
       android:hint="@string/enter_phone_number" />

   <ImageButton
       android:id="@+id/verify_otp"
       android:textColor="#fff"
       android:layout_width="48dp"
       android:layout_height="48dp"
       android:background="@drawable/button_next"
       android:src="@drawable/icon_right"/>

   </LinearLayout>

这是我在 Activity 中初始化手机片段的方式:

 private void initPhoneFragment(Bundle savedInstanceState) {
    if (findViewById(R.id.fragment_container) != null) {
        if (savedInstanceState != null) {
            return;
        }
        // Create a new Fragment to be placed in the activity layout
        GetPhone fragment = new GetPhone();
        // Pass the Intent's extras to the fragment as arguments
        fragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, fragment).commit();


    }
}

【问题讨论】:

  • 请不要重复提问。只需使用您拥有的任何新信息、您尝试过的任何新代码或任何已发布答案不起作用的解释来编辑您的原始帖子,就会将其推到活动队列的顶部。

标签: android android-fragments


【解决方案1】:

由于按钮属于fragment,所以处理按钮点击的应该是fragment,而不是activity。

在您的 GetPhone java 代码中,执行以下操作:

View btnVerify; //global variable

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.get_phone, container, false); //put the proper layout xml file name
    btnVerify = view.findViewById(R.id.verify_otp);
    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    btnVerify.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentManager fragmentManager = activityContext.getSupportFragmentManager();
            Fragment fragment = new OTP();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        }
    });
}

如果你想在activity中处理fragment的替换,那么你可以在fragment和activity之间创建一个接口,在onClick方法中进行回调,而不是直接进行事务。

更多信息:https://developer.android.com/guide/components/fragments#CommunicatingWithActivity

【讨论】:

  • 感谢您的回复。但这给了我一个空指针异常。我确实在加载 GetPhone 片段后放置了这段代码。
  • 请检查我修改后的答案
  • 是的,这解决了问题。我有一个错误的想法,因为片段是一个完全不同的文件,所以可能无法直接从片段传递函数,这会影响其父活动中的函数。今天也学到了一个新东西!
【解决方案2】:

试试这个,点击按钮

  OTP fragment = new OTP(); //OTP fragment
  FragmentManager fm = getFragmentManager();
  FragmentTransaction ft = fm.beginTransaction();
  ft.replace(R.id.frame_container, fragment);
  ft.addToBackStack(null);
  ft.commit();

【讨论】:

  • 感谢您的回复。但是,该按钮位于片段中。通过我的 Activity 访问按钮会生成 NullPointerException。
  • 您是否尝试通过活动访问片段中的按钮?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多