有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在屏幕中央的片段层上添加一个可点击的按钮

我想在屏幕中间添加一个片段的按钮,添加按钮,但不是点击和转到所需的活动。这是我的java&;xml:- xml代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:background="@drawable/a6">

    <Button
        安卓:id="@+id/hardware"
        安卓:layout_width="match_parent"
        安卓:layout_height="70dp"
        安卓:layout_alignParentBottom="true"
        安卓:layout_alignParentLeft="true"
        安卓:layout_alignParentStart="true"
        安卓:layout_marginBottom="213dp"
        安卓:background="@安卓:color/darker_gray"
        安卓:text="Button" />
</RelativeLayout> 

Java代码

public class SwapFragmentsix extends Fragment {
    Button hardware;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_swap_fragmentsix, container, false);
        hardware = (Button) view.findViewById(R.id.hardware);
        hardware.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HardwareKeyPoints.class);
                startActivity(intent);
            }
        });
        return inflater.inflate(R.layout.activity_swap_fragmentsix, container, false);
    }
}

enter image description here


共 (1) 个答案

  1. # 1 楼答案

    你应该试试这个

    public class SwapFragmentsix extends Fragment {
            Button hardware;
    
    
            @Override
            public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.activity_swap_fragmentsix, container, false);
                hardware = (Button) view.findViewById(R.id.hardware);
                hardware.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), HardwareKeyPoints.class);
                        startActivity(intent);
                    }
                });
                return view;  //change to this
            }
        }
    

    It is because of you are returning inflater.inflate(R.layout.activity_swap_fragmentsix, container,false); instead of view. That is you are inflating the view again.