【问题标题】:Toggle RadioButton in a custom row of ListView在 ListView 的自定义行中切换 RadioButton
【发布时间】:2017-12-31 02:29:55
【问题描述】:

每次打开目标 Activity 时,我都会遍历 ListView 中的自定义行以搜索特定值。

 private void setSelectedProfile() {
    SharedPreferences sp = getSharedPreferences("SPD", Context.MODE_PRIVATE);
    for (int i = 0; i < lv.getCount(); i++) {
        if (String.valueOf(lv.getItemAtPosition(i)).equals(sp.getString("default", ""))) {
            // code that I needed
            break;
        }
    }
}

一旦循环找到它,我需要切换自定义行内的单选按钮。我试图找到并应用他们的解决方案,但没有一个适合我的情况。

如何访问 RadioButton 以便切换它们?

谢谢。

【问题讨论】:

    标签: android listview android-activity


    【解决方案1】:

    在您的 ListView 适配器的 getView 方法中执行此操作。像这样的:

    public class MyAdapter extends ArrayAdapter<String> {
    
        private SharedPreferences sp;
        private List<String> data;
    
        public MyAdapter(@NonNull Context context, @NonNull List<String> data) {
            super(context, -1, data);
            this.data = data;     
            sp = context.getSharedPreferences("SPD", Context.MODE_PRIVATE);
        }
    
       @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
            // init views 
            RadioButton radioButton = (RadioButton ) rowView.findViewById(R.id.radioButton);
    
    
            // toggle the radio button 
            if (data.get(position).equals(sp.getString("default", ""))) {
                  radioButton.setChecked(!radioButton.isChecked());
            }
    
            // bind other views
    
            return rowView;
        }
    }
    

    【讨论】:

    • 就是这样!我盯着 getView 方法的代码块,但不知道要在那里添加什么。非常感谢!
    • @Mr.Nacho 我很高兴它有帮助:-)
    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    相关资源
    最近更新 更多