Кнопка OnClickListener не работает во фрагменте

#android #android-fragments

#Android #android-фрагменты

Вопрос:

Пытаюсь выполнить несколько простых вычислений, я установил прослушиватель на свой фрагмент, но он не запускает onClick метод, и журнал ничего не показывает, согласно принятому здесь ответу, это должно сработать, и большинство альтернатив не сработали для меня, в чем причина такого поведения Это мой фрагмент

 public class AttendanceFragment extends Fragment implements View.OnClickListener {
    EditText ET_days,ET_week;
    TextView TV_attendance;
    Button btn;
    static int attendance;
    public static final String TAG = "Checking";

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

        ET_days= (EditText) v.findViewById(R.id.et_days);
        ET_week= (EditText)v.findViewById(R.id.et_week);
        TV_attendance=(TextView) v.findViewById(R.id.tv_attendance);
        btn=(Button)v.findViewById(R.id.btn_attendance);
        btn.setOnClickListener(this);



        return v;
    }


    @Override
    public void onClick(View view) {
        int days =Integer.parseInt(ET_days.getText().toString());
        int week= Integer.parseInt(ET_week.getText().toString());
        int d = days * 5;
        int w = week * 75;

        attendance= (d/w) * 100;
        String att= String.valueOf(attendance);
        Log.d("ATtendance",att);

        TV_attendance.setText("Your Current Attendance is:" att);
    }

}
  

Это мой макет:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@ id/tv_days"
        android:text="Enter The number of days you have missed so Far"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        />
    <EditText
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:hint="days missed"
    android:id="@ id/et_days"
    />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@ id/tv_week"
        android:text="Enter The Current school week Number "
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        />
    <EditText
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:hint="week number"
        android:id="@ id/et_week"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Current Attendance is: 85%"
        android:layout_marginTop="40dp"
        android:textSize="30sp"
        android:id="@ id/tv_attendance"
        />

    <Button
        style="@style/Widget.AppCompat.Button.Borderless"

        android:layout_width="250dp"
        android:layout_height="60dp"
        android:id="@ id/btn_attendance"
        android:layout_marginTop="80dp"
        android:layout_gravity="center"
        android:text="Check Attendance"
        android:textSize="18sp"
        android:background="@drawable/button_selector"
        android:textColor="@color/white"


        />


</LinearLayout>
  

Редактировать:
фрагмент является частью 5 фрагментов в BottomBar , они находятся в моей MainActivity

 public class MainActivity extends AppCompatActivity {
    private int STORAGE_PERMISSION_CODE = 7;
    BottomBar mBottomBar;
   public static  int m= 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




        mBottomBar = BottomBar.attach(this,savedInstanceState);
        mBottomBar.setItemsFromMenu(R.menu.menu_main,new OnMenuTabClickListener()



        {


            public void onMenuTabSelected(@IdRes int i) {
                if(i==R.id.Bottombaritemone)
                {
                    NewsFRagment f = new NewsFRagment();
                    getSupportFragmentManager().beginTransaction().replace(R.id.main_container,f).commit();

                }
                else if(i==R.id.Bottombaritemtwo)
                {
                   AttendanceFragment f =new AttendanceFragment();
                    getSupportFragmentManager().beginTransaction().replace(R.id.main_container,f).commit();
                }
                else if(i==R.id.Bottombaritemthree)
                {
                    PhoneFragment f =new PhoneFragment();
                    getSupportFragmentManager().beginTransaction().replace(R.id.main_container,f).commit();

                }
                else if(i==R.id.Bottombaritemfour)
                {

                    UploadFragment f =new UploadFragment();
                    getSupportFragmentManager().beginTransaction().replace(R.id.main_container,f).commit();
                    if (m == 0) {


                        if (isReadStorageAllowed()) {
                            //If permission is already having then showing the toast
                            //Existing the method with return
                            return;
                        }

                        //If the app has not the permission then asking for the permission
                        requestStoragePermission();
                    }

                }
                else if(i==R.id.Bottombaritemfive)
                {
                    FavoritesFragment f =new FavoritesFragment();
                    getSupportFragmentManager().beginTransaction().replace(R.id.main_container,f).commit();
                }
            }



            @Override
            public void onMenuTabReSelected(@IdRes int i) {

            }
        });
        mBottomBar.mapColorForTab(0, "#F44336");
        mBottomBar.mapColorForTab(1,"#9C27B0");
        mBottomBar.mapColorForTab(2,"#03A9F4");
        mBottomBar.mapColorForTab(3,"#795548");
        mBottomBar.mapColorForTab(4,"#FF6F00");

        BottomBarBadge unread;
        unread = mBottomBar.makeBadgeForTabAt(3,"#FF0000",13);
        unread.show();


    }


    //We are calling this method to check the permission status
    private boolean isReadStorageAllowed() {
        //Getting the permission status
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);

        //If permission is granted returning true
        if (result == PackageManager.PERMISSION_GRANTED)
            return true;

        //If permission is not granted returning false
        return false;
    }

    //Requesting permission
    private void requestStoragePermission(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){
            //If the user has denied the permission previously your code will come to this block
            //Here you can explain why you need this permission
            //Explain here why you need this permission
            Toast.makeText(MainActivity.this,"Need permission to read fles for upload",Toast.LENGTH_LONG).show();

        }

        //And finally ask for the permission
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
        Log.d("Permission Requested","Permission requested");
    }

    //This method will be called when the user will tap on allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        //Checking the request code of our request
        if(requestCode == STORAGE_PERMISSION_CODE){

            //If permission is granted
            if(grantResults.length >0 amp;amp; grantResults[0] == PackageManager.PERMISSION_GRANTED){

                //Displaying a toast
                Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
            }else{
                //Displaying another toast if permission is not granted
                Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
            }
        }
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


}
  

Комментарии:

1. но вы не вызываете onClick в теге <Кнопка>

2. это необходимо, несмотря на слушателя?? извините, я новичок, так какой метод мне ввести в тег onClick в xml

3. Вы поместили точку останова внутри onClick, чтобы убедиться, что она никогда не вызывалась?. Что касается других комментариев, вам не нужно добавлять onClick в XML, достаточно добавить чисто в коде, и это просто другой способ сделать это..

4. Я регистрируюсь внутри onClick, журнал не отображается в Logcat

5. Как этот фрагмент позиционируется по сравнению с активностью или другими фрагментами. Возможно, у вас есть другой фрагмент или представление, который перекрывает кнопку, препятствуя ее нажатию?

Ответ №1:

Попробуйте это

 @Override
 public void onClick(View view) {
     switch (view.getId()){

     case R.id.R.id.btn_attendance:
 int days =Integer.parseInt(ET_days.getText().toString());
 int week= Integer.parseInt(ET_week.getText().toString());
 int d = days * 5;
 int w = week * 75;
 attendance= (d/w) * 100;
 String att= String.valueOf(attendance);
 Log.d("ATtendance",att);
 TV_attendance.setText("Your Current Attendance is:" att);
 break;
 }
}
  

Теперь он должен работать так, как вы хотите

Комментарии:

1. По-прежнему ничего, ничего в Logcat, это настоящая головная боль

2. попробуйте очистить и перестроить проект. Просто для попытки

3. По-прежнему не повезло, я использую инструменты сборки 24.0.0, если это вообще поможет