2016-09-29 3 views
0

Я пытаюсь выполнить некоторые простые вычисления, я установил прослушиватель на свой фрагмент. Но он не вызывает метод onClick, и журнал ничего не показывает. Согласно принятому здесь отвечу, это должно работать, и большинство альтернатив не работает для меня, Что является причиной такого поведения Это мой фрагментКнопка onClickListener не работает во фрагменте

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> 

EDIT: фрагмент является частью 5 fragents в 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 && 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; 
    } 


} 
+0

, но не вызывать OnClick в теге

+0

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

+1

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

ответ

0

Попробуйте

@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; 
} 
} 

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

+0

Все еще ничего, ничего в Logcat, это это настоящая головная боль –

+0

попробуйте очистить и перестроить проект. Просто попробуйте – androidXP

+0

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

Смежные вопросы