【发布时间】: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();
}
}
【问题讨论】:
-
请不要重复提问。只需使用您拥有的任何新信息、您尝试过的任何新代码或任何已发布答案不起作用的解释来编辑您的原始帖子,就会将其推到活动队列的顶部。