[英]How to get next activity when clicked from frag button
Hi i am trying to get my NextActivity when i press on Fab in my View 1嗨,当我在视图 1 中按下 Fab 时,我正在尝试获取我的 NextActivity
View 1 xml查看 1 个 xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/Fbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="180dp"
android:clickable="true"
android:paddingRight="16dp"
android:paddingBottom="16dp"
/>
</RelativeLayout>,
View.java查看.java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class View1 extends Fragment {
private FloatingActionButton mFab;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.view1, container, false);
mFab.findViewById(R.id.Fbutton);
mFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),NextActivity.class);
startActivity(intent);
}
});
return view;
}
}
Error错误
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.floatingactionbutton.FloatingActionButton.findViewById(int)' on a null object reference at com.example.myapplication.View1.onCreateView(View1.java:21) java.lang.NullPointerException:尝试在 com.example.myapplication.View1.onCreateView( View1.java:21)
i have tried getContext() View1.this nothing worked我试过getContext() View1.this没有任何效果
You haven't complete the floating button assigning.您尚未完成浮动按钮分配。 Remove
mFab.findViewById(R.id.Fbutton);
删除
mFab.findViewById(R.id.Fbutton);
this line.这条线。 Add
添加
mFab = view.findViewById(R.id.Fbutton);
Here view
is used to get the ID from the layout.这里的
view
用于从布局中获取 ID。
From the code that you posted most probably the problem is that you are not assigning the return value of findViewById(R.id.Fbutton);从您发布的代码中最有可能的问题是您没有分配findViewById(R.id.Fbutton);的返回值; to the mFab .
到mFab 。
mFab = findViewById(R.id.Fbutton);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.