imageview.setOnClickListener在子视图中不起作用

时间:2015-10-31 09:45:12

标签: android

就像标题一样,以下是代码,子视图中的图片效果不好,请帮我找原因,谢谢。

for (int i = 0; i < 3; i++) {
    View parentView = getActivity().getLayoutInflater().inflate(R.layout.horizontal_scrollview, verticalScrollView, false);
    horizontalScrollview = (LinearLayout) parentView.findViewById(R.id.horizontalScrollParentLayout);
    texthead = (TextView) parentView.findViewById(R.id.txthead);
    texthead.setText("Heading" + i);

    for (int j = 0; j < 6; j++) {
         View childView = getActivity().getLayoutInflater().inflate(R.layout.horizontal_scroll_child, verticalScrollView, false);
         childLayout = (LinearLayout) childView.findViewById(R.id.child_layout);
         image = (ImageView) childLayout.findViewById(R.id.image);
         image.setImageResource(R.drawable.home);
         text = (TextView) childLayout.findViewById(R.id.text);
         text.setText("Detail" + j);
         horizontalScrollview.addView(childView);
     }

     verticalScrollView.addView(parentView);
 }

 image.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          Toast.makeText(getActivity(),"Hi",Toast.LENGTH_LONG).show();    
      }
 });

//end image click event not work

1 个答案:

答案 0 :(得分:0)

你应该在循环中添加image.setOnClickListener,在你的代码中,你最后添加onclicklistener,但它只能添加到你找到的最后一个imageview。所以请试试这个:

  for (int i = 0; i < 3; i++) {
      View parentView =   getActivity().getLayoutInflater().inflate(R.layout.horizontal_scrollview, verticalScrollView, false);
      horizontalScrollview = (LinearLayout) parentView.findViewById(R.id.horizontalScrollParentLayout);
      texthead = (TextView) parentView.findViewById(R.id.txthead);
      texthead.setText("Heading" + i);
      for (int j = 0; j < 6; j++) {
         View childView = getActivity().getLayoutInflater().inflate(R.layout.horizontal_scroll_child, verticalScrollView, false);
         childLayout = (LinearLayout) childView.findViewById(R.id.child_layout);
         image = (ImageView) childLayout.findViewById(R.id.image);
         image.setImageResource(R.drawable.home);
         image.setOnClickListener(new View.OnClickListener() {
         @Override
             public void onClick(View v) {
                 Toast.makeText(getActivity(),"Hi",Toast.LENGTH_LONG).show();    
             }
         });
         text = (TextView) childLayout.findViewById(R.id.text);
         text.setText("Detail" + j);
         horizontalScrollview.addView(childView);
     }

     verticalScrollView.addView(parentView);
 }