如何将按钮点击从片段传递到主要活动

时间:2019-08-19 22:03:15

标签: android android-fragments

我试图通过MainActivity访问GetPhone片段中名为kernel[0][0] = 0.1 kernel[1][0] = 0.2 kernel[2][0] = 0.3 kernel[0][1] = 0.5 kernel[1][1] = 0.6 kernel[2][1] = 0.7 kernel[0][2] = 0.9 kernel[1][2] = 1.0 kernel[2][2] = 1.0 的按钮。

我尝试使用 verify_otp,但这会创建NullPointerException。

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

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

btnVerify = findViewById(R.id.verify_otp)

在我的主要活动中称呼它:

public ImageButton getMyButton(){
return myButton;
}

这还会产生NullPointerException。

这是我的GetPhone片段:

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

这是我在“活动”中初始化手机片段的方式:

<?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>

2 个答案:

答案 0 :(得分:1)

由于按钮属于片段,应该是处理按钮单击的片段,而不是活动。

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

SS.Range("C2").Copy
DS.Range("F4").PasteSpecial xlPasteValues

如果要处理活动中片段的替换,则可以在片段和活动之间创建接口,并使用onClick方法执行回调,而不是直接进行事务。

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

答案 1 :(得分:1)

尝试,点击按钮

  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();
相关问题