在片段中初始化多个ImageButton并在所有片段中添加SetOnClickListener

时间:2016-06-04 05:42:29

标签: android-fragments android-studio onclicklistener buttonclick

公共类MenFragment扩展片段{

ImageButton imageButtonCald;
ImageButton imageButtonCk;
ImageButton imageButtonCr;
ImageButton imageButtonTLt;
ImageButton imageButtonSttic;
ImageButton imageButtonSh;
View rootView;


public MenFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_men, container, false);
    imageButtonCald = (ImageButton) rootView.findViewById(R.id.cald);
    imageButtonCk = (ImageButton) rootView.findViewById(R.id.ck);
    imageButtonCr = (ImageButton) rootView.findViewById(R.id.cr);
    imageButtonTLt = (ImageButton) rootView.findViewById(R.id.tlt);
    imageButtonSttic = (ImageButton) rootView.findViewById(R.id.sttc);
    imageButtonSch = (ImageButton) rootView.findViewById(R.id.sch);


    /*here i add a setOnClickListener method the my first button , how to add to the one */
    imageButtonCald.setOnClickListener(new View.OnClickListener()  {
        @Override
        public void onClick(View v) {
            Intent intent;
            intent = new Intent(getActivity(), CaldActivity.class);
            startActivity(intent);
        }
    });
    return rootView;
}
}

我已经在第一个按钮上添加了'setOnClickListener',如何在另一个按钮上添加'setOnClickListener'。

1 个答案:

答案 0 :(得分:1)

您需要在片段中实现onClicklistener。

public static class PlaceholderFragment extends Fragment implements OnClickListener {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
 View rootView = inflater.inflate(R.layout.fragment_main, container,
        false);

 Button button1 = (Button) rootView.findViewById(R.id.try_button1);     
 Button button2 = (Button) rootView.findViewById(R.id.try_button2);    
 Button button3 = (Button) rootView.findViewById(R.id.try_button3);     
 button1.setOnClickListener(this);
 button2.setOnClickListener(this);
 button3.setOnClickListener(this);

 return rootView;
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int viedId = v.getId();
 switch(viedId ){
  case R.id.try_button1:
  //your implementation here
  break;
  case R.id.try_button2:
  //your implementation here
  break;
  case R.id.try_button3:
  //your implementation here
  break;

 }
}

}
}