如何在片段中使用切换按钮

时间:2014-08-11 07:51:18

标签: android

这是我的类代码,其中我想访问切换按钮,但是我得到nullpointer exception.i使用ViewHolder类从布局获取视图并在此处访问它们。但是无法找到错误为什么在        holder.stateOnOff.setText();线

 public class ColorSchemeFragment extends Fragment {

public  class ViewHolder {
    public  ToggleButton toggleButton;
    public TextView stateOnOff;
}
ViewHolder holder = new ViewHolder();

@Override
public View onCreateView(LayoutInflater inflater, 
 ViewGroup container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.colorscheme, container, false);
    holder.toggleButton = ((ToggleButton) container.findViewById(R.id.toggle));
    holder.stateOnOff=(TextView)container.findViewById(R.id.tvstate);
    holder.stateOnOff.setText("OFF");
    holder.toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            if(isChecked){
                holder.stateOnOff.setText("On");
            }else{
                holder.stateOnOff.setText("Off");
            }
                }
            });
        return view;
        }
       }

1 个答案:

答案 0 :(得分:2)

无需使用ViewHolder。它们用于通过ListView或其他可滚动视图回收视图。

container对象还包含父布局,而不是您要膨胀的布局。因此它不包含您正在查找的视图并返回null。

public class ColorSchemeFragment extends Fragment {

public ToggleButton toggleButton;
public TextView stateOnOff;

@Override
public View onCreateView(LayoutInflater inflater, 
 ViewGroup container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.colorscheme, container, false);
    toggleButton = (ToggleButton) view.findViewById(R.id.toggle);
    stateOnOff=(TextView) view.findViewById(R.id.tvstate);
    stateOnOff.setText("OFF");
    toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
            if(isChecked){
                stateOnOff.setText("On");
            }else{
                stateOnOff.setText("Off");
            }
                }
            });
        return view;
        }
     }