如何在Fragment中添加onClick

时间:2017-06-11 13:26:11

标签: java android android-fragments

您好我想在Fragment中将onClick选项添加到ImageView。 我试了几件但失败了。 这是我的Fragmet.java

public class Info扩展Fragment {

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    return inflater.inflate(R.layout.info, container, false);
}

}

3 个答案:

答案 0 :(得分:1)

覆盖

  @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

并使用view对象(与View中返回的onCreateView相同)来查找要在其上设置onClickListener的ImageView。 E.g。

  @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        View imageView = view.findViewById(R.id.id_of_image_view);
        imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
  }

答案 1 :(得分:0)

不要直接返回视图,而是执行此操作

View v=inflater.inflate(R.layout.info, container, false);

然后您可以使用v查找对ImageViews的引用

ImageView iv=(ImageView)v.findViewById(R.id.imageview_id);

然后像往常一样设置onClickListener

iv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //do something
        }
    });

答案 2 :(得分:0)

ImageView中必须有layout R.layout.info. 如果ImageView的ID为ivInLayout,则可以设置onClik这样的内容:

public class Info extends Fragment{

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.info, container, false);

        ImageView iv = (ImageView) v.findViwById(R.id.ivInLayout);
        iv.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(){
                 <What you want onClick on the image to do>
            }
        });
        return v;
    }

}