“ onRadioButtonClicked”方法不适用于由“ onCreate”方法实现的单选按钮

时间:2018-09-07 21:58:18

标签: java android android-studio listview

我试图在“ onCreateMethod”上填充RadioGroup的RadioButton,而不是使用XML,因为我的目的是从某种具有随机性的数据库或其他业务对象模型中获取它。 RadioButtons很好,但是当我单击它们时什么也不会发生,否则当我在XML活动文件中创建时既没有日志消息也没有测试吐司。顺便说一句,正如我所说,我需要通过代码创建按钮,谢谢,这是我在Android中的第一步。

我的活动XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>

我的代码:

public class ListaAlunosActivity extends AppCompatActivity {


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_alunos);

        LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
        // Log.d(TAG,"Populate List View; Displaying Data in the List View");

        ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
        RadioGroup listaDeQuestoes = new RadioGroup(this);
        listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
        RadioGroup.LayoutParams lp;

        for (int i = 0; i < dataList.size(); i++) {
            RadioButton botao = new RadioButton(this);
            botao.setText(dataList.get(i));
            lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
            listaDeQuestoes.addView(botao, lp);
        }
        questoesQuiz.addView(listaDeQuestoes);
    }


    public void onRadioButtonClicked(View view) {

        boolean checked = ((RadioButton) view).isChecked();


        final String TAG = "MyActivity";


        Log.v("On clicked working", "clicado");

        int id = view.getId();


        Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
        toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
        toast2.show();
  }
}

按钮还可以!

Buttons are okay

4 个答案:

答案 0 :(得分:2)

使用onClick查找选定的单选按钮不是最好的解决方案,但是因为您想使用onClick,所以我将向您展示如何在对代码进行最少更改的情况下进行操作。对您的代码进行以下三个更改:

public class ListaAlunosActivity extends AppCompatActivity 
        implements View.OnClickListener {// <------ 1. implement OnClickListener

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_alunos);

        LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
        // Log.d(TAG,"Populate List View; Displaying Data in the List View");

        ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
        RadioGroup listaDeQuestoes = new RadioGroup(this);
        listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
        RadioGroup.LayoutParams lp;

        for (int i = 0; i < dataList.size(); i++) {
            RadioButton botao = new RadioButton(this);
            botao.setOnClickListener(this);//  <---------- 2.add this line
            botao.setText(dataList.get(i));
            lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
            listaDeQuestoes.addView(botao, lp);
        }
        questoesQuiz.addView(listaDeQuestoes);
    }
@Override
public abstract void onClick (View v){ //<-------- 3. override onClick
   boolean checked = ((RadioButton) v).isChecked();


        final String TAG = "MyActivity";


        Log.v("On clicked working", "clicado");

        int id = v.getId();// your radio buttons have no id thus use title instead of id:
        String title = ((RadioButton) v).getText();


        Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
        toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
        toast2.show();
}

答案 1 :(得分:2)

如果您敏锐地看待,则onRadioButtonClicked只是一个永远不会调用的方法。现在,您需要做的是使Activity实现RadioGroup.OnCheckedChangeListener。然后在onCheckedChanged方法中执行Toast,它将起作用。这是代码。

public class ListaAlunosActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lista_alnus);

    LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
    // Log.d(TAG,"Populate List View; Displaying Data in the List View");

    ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
    RadioGroup listaDeQuestoes = new RadioGroup(this);
    listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
    RadioGroup.LayoutParams lp;

    for (int i = 0; i < dataList.size(); i++) {
        RadioButton botao = new RadioButton(this);
        botao.setId(i);
        botao.setText(dataList.get(i));
        lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
        listaDeQuestoes.addView(botao, lp);
    }
    questoesQuiz.addView(listaDeQuestoes);

    listaDeQuestoes.setOnCheckedChangeListener(this);
}



@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
    Toast toast2 = Toast.makeText(this, "toast working for id "+ checkedId, Toast.LENGTH_LONG);
    toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
    toast2.show();

}

}

我做到了,而且效果很好

答案 2 :(得分:2)

不能完全确定代码的用途,但是我将使用setOnCheckedChangeListener而不是onClick。

类似这样的东西

    listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            final String TAG = "MyActivity"; // not used?

            Log.v("On clicked working", "clicado");

            // Note checkedId is +1 when accessing the arraylist so needs to be decremented to get a list item
            Toast toast2 = Toast.makeText(ListaAlunosActivity.this, "toast working clicked (" + checkedId + ") [" + dataList.get(checkedId - 1) + "]", Toast.LENGTH_LONG);
            toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
            toast2.show();
        }
    });

Toast正在运行,并且我向您展示了如何确定单击了哪个按钮以及如何根据需要访问数据数组。

答案 3 :(得分:2)

正如BAHMAN指出的,这样做的主要原因是您尚未设置任何侦听器。然而。在按钮本身上设置侦听器不是一个好主意。最好将其设置在广播组上。并且最好在布局文件中包含布局元素。这使它们更易于修改和理解。

另一件事是个人喜好:我更喜欢将侦听器实现为设置了它的匿名类。该类实现了侦听器的解决方案使大型类难以阅读,而大型类可能会讨厌寻找侦听器。如果侦听器非常复杂,或者它可能被多次使用,那么我可能会例外。

我也整理了一下代码。评论添加了我做的地方

无论如何,这是我编写此代码的方式:

主要活动布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/quiz"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RadioGroup
        android:id="@+id/radio_button_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

主要活动代码:

public class ListaAlunosActivity extends AppCompatActivity {
    // I put your tag at the top of the class so it's more useful
    public static final String TAG = "ListaAlunosActivity"; 

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_alunos);

        // You didn't really need an arraylist here for this static content.
        // I just made it an array
        String[] dataList = {"sup1", "sup2", "sup3"}; 

        // Get this from your layout instead of adding it manually.
        // It's a cleaner way to set up the layout that makes the
        // code more maintainable
        RadioGroup listaDeQuestoes = findViewById(R.id.radio_button_list);

        // I changed this to a for each loop because it's a little cleaner
        for (String name : dataList){
            RadioButton botao = new RadioButton(this);
            botao.setText(name);
            listaDeQuestoes.addView(botao);
        }

        // This is the code that will react to the new radio button being selected 
        listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // Either way we do it, we need to grab the view to get the name
                RadioButton buttonView = group.findViewById(checkedId);

                // You can use this code to get the index if you need it
                int checkedIndex = group.indexOfChild(buttonView);

                // And you can use either of these methods to get the name:
                String buttonNameFromView = buttonView.getText().toString();
                String buttonNameFromDataSource = dataList[checkedIndex];

                String output = "Button with Id: " + checkedId + " and Name: " + buttonNameFromView + " was clicked";

                Log.v(TAG, output);

                Toast toast = Toast.makeText(ListaAlunosActivity.this, output, Toast.LENGTH_LONG);
                // I set gravity to just center here.  This is the same as center_vertical | center_horizontal.  Personally, I wouldn't set it at all.
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        });
    }
}