【问题标题】:How to add buttons toast message "onClick" in fragment如何在片段中添加按钮吐司消息“onClick”
【发布时间】:2020-04-02 14:10:11
【问题描述】:

我想在用户单击按钮时显示 Toast 消息。

我尝试了很多解决方案,但对我不起作用。

这里是代码

Java “AccountFragment”

public class AccountFragment extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_account, container, false);

    // return the view "Layout"
    return rootView;
}

// display message for the user
public void Tosta (View view) {
    Toast.makeText(getActivity() , "There is no need to Login because you are a tester :D" , Toast.LENGTH_LONG).show();
}}

XML“fragment_account” 我用过点击

<Button
    android:id="@+id/button_login_google"
    android:layout_width="261dp"
    android:layout_height="50dp"
    android:layout_marginTop="50dp"
    android:background="@drawable/account_view2"
    android:text="Login with Google"
    android:onClick="Tosta"
    android:textColor="#fff"
    android:textSize="18dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView_login" />

【问题讨论】:

    标签: java android xml android-fragments toast


    【解决方案1】:

    看看这个:

         public class AccountFragment extends Fragment {
    
            Button btn;
    
            @Nullable
            @Override
            public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_account, container, false);
    
               btn = (Button) rootView.findViewById(R.id.button_login_google);
            btn.setOnClickListener(this);
                return rootView;
            }
    
            // display message for the user
            @Override
            public void onClick(View v) {
                // Toast here
        Toast.makeText(getActivity(),  "toast", Toast.LENGTH_LONG).show();
            }
    }
    

    你也可以试试这个:

    btn.setOnClickListener(new OnClickListener() {
    
                        @Override
                        public void onClick(View arg0) {
    
                        Toast.makeText(getActivity(),  "toast", Toast.LENGTH_LONG).show();
    
                        }
                    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      相关资源
      最近更新 更多