2016-12-15 2 views
0

У меня есть вкладка, и в одном из фрагментов у меня есть группа радиостанций с тремя переключателями. Я пытаюсь выяснить, как определить, какие переключатели выбраны. Я подозреваю, что мне нужно сделать java-файл для фрагмента. Однако я не уверен, что это правильно. Я последовал примеру Java-файла. Я изменил его, и он не работает. Ничего не происходит, когда я нажимаю на переключатель.Использование переключателей в фрагменте с вкладками

fragment_calories_want.xml (опущено код не имеет отношения к вопросу)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="layout.CaloriesWant"> 

    <RadioGroup 
     android:layout_width="match_parent" 
     android:layout_height="100px" 
     android:id="@+id/radioGroup" 
     android:orientation="horizontal" 
     android:layout_marginTop="82dp" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true"> 

     <RadioButton 
      android:text="Grams" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/radioButtonGrams" 
      android:layout_weight="1" 
      tools:text="Grams" /> 

     <RadioButton 
      android:text="Ounces" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/radioButtonOunces" 
      android:layout_weight="1" /> 

     <RadioButton 
      android:text="Pounds" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/radioButtonPounds" /> 
    </RadioGroup> 
</RelativeLayout> 

CaloriesWantFragment.java

package com.example.crims.caloriecalculator; 
import android.app.Activity; 
import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.RadioButton; 
import android.widget.RadioGroup; 
import android.widget.Toast; 

public class CaloriesWantFragment extends Fragment { 

    private RadioButton radioButton1; 
    private RadioButton radioButton2; 
    private RadioButton radioButton3; 
    private RadioGroup radioGroupOne; 
    String buttonSelected; 
    Activity activity; 


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


     final View view = inflater.inflate(R.layout.fragment_calories_want, container, false); 
     radioButton1 = (RadioButton) view.findViewById(R.id.radioButtonGrams); 
     radioButton2 = (RadioButton) view.findViewById(R.id.radioButtonOunces); 
     radioButton3 = (RadioButton) view.findViewById(R.id.radioButtonPounds); 
     radioGroupOne = (RadioGroup) view.findViewById(R.id.radioGroup); 

     radioGroupOne.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(RadioGroup radioGroup, int i) { 
       switch(i){ 
        case R.id.radioButtonGrams: 
         buttonSelected = "button one selected"; 

         break; 
        case R.id.radioButtonOunces: 
         buttonSelected = "button two selected"; 

         break; 
        case R.id.radioButtonPounds: 
         buttonSelected = "button three selected"; 

         break; 
        default: 

       } 
       Toast.makeText(activity, "radio button selected " + buttonSelected, Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     return view; 
    } 

} 
+0

Где вы пишете строку findViewById для RadioGroup? –

+0

вы можете использовать 'radioGroup.getCheckedRadioButtonId();', чтобы получить выбранный идентификатор кнопки –

+0

@RishabhMahatha Я просто добавил его. файл обновлен и по-прежнему имеет такую ​​же проблему. Ожидая тоста, чтобы отобразить что-то, когда я нажимаю кнопку. – crims

ответ

2

Initialize Radio Group

radioGroupOne = (RadioGroup) view.findViewById(R.id.radioGroup); 

Java файл

public class CaloriesWantFragment extends AppCompatActivity { 

    private RadioButton radioButton1; 
    private RadioButton radioButton2; 
    private RadioButton radioButton3; 
    private RadioGroup radioGroupOne; 
    String buttonSelected; 
    Activity activity; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 

     radioButton1 = (RadioButton) findViewById(R.id.radioButtonGrams); 
     radioButton2 = (RadioButton) findViewById(R.id.radioButtonOunces); 
     radioButton3 = (RadioButton) findViewById(R.id.radioButtonPounds); 
     radioGroupOne = (RadioGroup) findViewById(R.id.radioGroup); 

     radioGroupOne.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
      @Override 
      public void onCheckedChanged(RadioGroup radioGroup, int i) { 
       switch (i) { 
        case R.id.radioButtonGrams: 
         buttonSelected = "button one selected"; 

         break; 
        case R.id.radioButtonOunces: 
         buttonSelected = "button two selected"; 

         break; 
        case R.id.radioButtonPounds: 
         buttonSelected = "button three selected"; 

         break; 
        default: 

       } 
       Toast.makeText(CaloriesWantFragment.this, "radio button selected " + buttonSelected, Toast.LENGTH_SHORT).show(); 
      } 
     }); 
    } 

Xml файл

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <RadioGroup 
     android:layout_width="match_parent" 
     android:layout_height="100px" 
     android:id="@+id/radioGroup" 
     android:orientation="horizontal" 
     android:layout_marginTop="82dp" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true"> 

     <RadioButton 
      android:text="Grams" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/radioButtonGrams" 
      android:layout_weight="1" 
      tools:text="Grams" /> 

     <RadioButton 
      android:text="Ounces" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/radioButtonOunces" 
      android:layout_weight="1" /> 

     <RadioButton 
      android:text="Pounds" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/radioButtonPounds" /> 
    </RadioGroup> 
</RelativeLayout> 
+0

ладно спасибо, я сделал это, и ничего не происходит. Я ожидаю, что тост покажет, какая кнопка была нажата. – crims

+0

Я скопировал и вставил код. Я смог получить его для компиляции/сборки. Он не работает (нет тостов). Единственная проблема, с которой я столкнулся, это строка setContentView (R.layout.fragment_calories_want) ;. Я изменил R.test в свой XML-файл, это правильно? – crims

+0

пришлите мне свой код –

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