【问题标题】:Android OnClickListener not working in fragmentAndroid OnClickListener 在片段中不起作用
【发布时间】:2021-01-17 22:58:47
【问题描述】:

我有一个片段显示了我从 firebase 中提取的用户详细信息。我正在尝试设置一个 OnClickListener 以便登录的用户可以更改他们的图像,但我似乎无法让它工作。我查看了日志 Cat 并且看不到任何错误。我看过其他人做类似的事情,但似乎无法找出为什么我的不起作用。

编辑:我发现了问题,但现在有一个不同的问题当片段第一次加载时,Onlick 在我刷新片段之前不起作用,然后 Onclick 起作用,但我不知道为什么片段需要刷新让 Onclick 工作?

片段;

 ImageView adminImage;

  adminImage = v.findViewById(R.id.AdminProfilePicture);
        adminImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(),"Long hold to change image",Toast.LENGTH_SHORT).show();
            }
        });


       adminImage.setOnLongClickListener(new View.OnLongClickListener() {
           @Override
           public boolean onLongClick(View view) {
               Intent openGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(openGallery,1000);
               return false;
           }
       });

设置fragment的主Activity;

   navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_Account_admin:
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                new ProfileAdminFragment()).commit();
                        break;
                    case R.id.nav_Games:
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                new GamesAdminFragment()).commit();

                        break;
                    case R.id.nav_Users:
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                new AllUsersAdminFragment()).commit();

                        break;
                    case R.id.nav_Fixture:
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                new FixturesAdminFragment()).commit();

                        break;

                    case R.id.nav_News:
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                new NewsAdminFragment()).commit();
                        break;
                    case R.id.nav_Contact:
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                new ContactAdminFragment()).commit();

                        break;
                    default:

                }
                draw.closeDrawer(GravityCompat.START);
                return true;
            }
        });

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, draw, toolbar,
                R.string.nav_app_bar_open_drawer_description, R.string.navigation_drawer_close);
        draw.addDrawerListener(toggle);
        toggle.syncState();

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ProfileFragment()).commit();
            navigationView.setCheckedItem(R.id.nav_Account);
        }
    }

XML;

 <RelativeLayout
        android:id="@+id/rellay1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/grad"
        android:paddingBottom="20dp">

        <RelativeLayout
            android:id="@+id/imageViewMain"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="20dp"
            android:background="@drawable/circle_border">


            <ImageView
                android:id="@+id/AdminProfilePicture"
                android:layout_width="120dp"
                android:layout_height="120dp"
                android:layout_margin="9dp"
                android:adjustViewBounds="true"
                android:background="@drawable/circle"
                android:padding="3dp"
                android:scaleType="centerInside"
                android:src="@drawable/ic_user" />

        </RelativeLayout>

Img of XML

完整的片段代码

public class ProfileAdminFragment extends Fragment {
    FirebaseAuth fAuth;
    FirebaseFirestore fStore;
    TextView uName, uEmail, uPhone;
    FusedLocationProviderClient fusedLocationProviderClient;
    TextView userlocation;
    ImageView adminImage;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View v = inflater.inflate(R.layout.fragment_profile_admin, container, false);

        fAuth = FirebaseAuth.getInstance();
        fStore = FirebaseFirestore.getInstance();


        userlocation = v.findViewById(R.id.tv_location);
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            //   getLocation();
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
        }


        uName = v.findViewById(R.id.profileFullName);
        uEmail = v.findViewById(R.id.profileEmail);
        uPhone = v.findViewById(R.id.profilePhone);

        DocumentReference docR = fStore.collection("Users").document(fAuth.getCurrentUser().getUid());
        docR.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if (documentSnapshot.exists()) {
                    uName.setText(documentSnapshot.getString("FullName"));
                    uEmail.setText(documentSnapshot.getString("UserEmail"));
                    uPhone.setText(documentSnapshot.getString("PhoneNumber"));
                }
            }
        });
        getLocation();
        // profile image
        adminImage = v.findViewById(R.id.AdminProfilePicture);
        adminImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Long hold to change image", Toast.LENGTH_SHORT).show();
            }
        });


        adminImage.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Intent openGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(openGallery, 1000);
                return false;
            }
        });


        return v;

    }

【问题讨论】:

  • 发布完整代码,此图片完整帮助
  • 您的长按是否有效?
  • 不,两个 OnClickListener 都不起作用
  • 你能粘贴你的片段代码,你膨胀视图的部分,并设置监听器
  • 在那里添加了片段的完整代码

标签: java android android-fragments onclicklistener


【解决方案1】:

请尝试在ImageView中添加android:clickable="true"。

<RelativeLayout
    android:id="@+id/rellay1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/grad"
    android:paddingBottom="20dp">

    <RelativeLayout
        android:id="@+id/imageViewMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@drawable/circle_border">


        <ImageView
            android:id="@+id/AdminProfilePicture"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:layout_margin="9dp"
            android:adjustViewBounds="true"
            android:background="@drawable/circle"
            android:padding="3dp"
            android:scaleType="centerInside"
            android:src="@drawable/ic_user"
            android:clickable="true" />

    </RelativeLayout>

【讨论】:

    【解决方案2】:

    例如,如果您从活动 a 调用片段, 然后 : 将片段中的 v 初始化为 public static 。之后从活动 a 调用 setOnClickListener。

    在你的活动中:

    YourFragment.v.findViewById("AdminProfilePicture").setOnClickListener (...);
    

    如果解决了您的问题请回复

    【讨论】:

      【解决方案3】:

      已解决 所以我发现我正在加载我的用户配置文件而不是我的管理员配置文件,因此加载片段时存在冲突,因此为了让 Onclick 正常工作,我必须手动刷新片段

      从此;

      new ProfileFragment()).commit();
      

      到这个;

      new ProfileAdminFragment()).commit();
      
        if (savedInstanceState == null) {
                  getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                          new ProfileAdminFragment()).commit();
                  navigationView.setCheckedItem(R.id.nav_Account_admin);
              }
      

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 2017-06-15
        • 1970-01-01
        • 2020-04-03
        • 2013-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多