如何在horizo​​ntalscrollview的点击监听器上实现

时间:2012-11-06 17:13:28

标签: android android-layout

我已经实现了Horizo​​ntalScrollView来显示图像。但我无法找到实现特定图像onclick监听器的方法,点击Horizo​​ntalScrollView。

我在imageview 1上实现了onclick也是我在imageview中调用但是在toast消息中它只显示“14”..

任何人都请帮帮我

更新

感谢山姆他指出了错误; 现在我想在每张图片下方显示文字。 所以我试图实现相对布局和代码,但它不起作用。

这是我的代码

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.cfragment, container, false);
    }
@Override
public void onStart() {
    super.onStart();
    /** Setting the multiselect choice mode for the listview */
    initfrag();
}
private void initfrag() {
    RelativeLayout layout = new RelativeLayout(getActivity());
     TextView tv1 = new TextView(getActivity());
     tv1.setText("xyzxyzyxyzxyz"); tv1.setId(1);
     TextView tv2 = new TextView(getActivity());
     tv2.setText("xyzxyzyxyzxyz");tv2.setId(2);
     RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
             RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
     lp.addRule(RelativeLayout.BELOW, tv1.getId());
     layout.addView(tv1);        
     layout.addView(tv2, lp);
    final LinearLayout linearlayout1 = (LinearLayout)getView().findViewById(R.id.container);
    LinearLayout linearlayout2 = (LinearLayout)getView().findViewById(R.id.container2);
    LinearLayout linearlayout3 = (LinearLayout)getView().findViewById(R.id.container3);
    for (int i = 0; i < 15; i++) { 
        iv = new ImageView(getActivity());
        iv.setPadding(20, 5, 5, 5);
        iv.setId(i);
         iv.setImageResource(R.drawable.test_play_image);
         linearlayout1.addView(iv, 200, 220);
         ImageView iv2 = new ImageView(getActivity());
         iv2.setPadding(20, 5, 5, 5);
         iv2.setImageResource(R.drawable.test_play_image);
         linearlayout2.addView(iv2, 200, 220);

         ImageView iv3 = new ImageView(getActivity());
            iv3.setPadding(20, 5, 5, 5);
             iv3.setImageResource(R.drawable.test_play_image);
             linearlayout3.addView(iv3, 200, 220);
             iv.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    int s =iv.getId();
                    Toast t = Toast.makeText(getActivity(), "id is "+s, Toast.LENGTH_SHORT);
                    t.show();
                }
            });

1 个答案:

答案 0 :(得分:1)

您希望获取刚刚单击的View的ID,而不是循环中创建的最后一个View。因此,只需从iv

更改OnClickListener中的变量即可
int s =iv.getId();

v,视图会传递到onClick()

int s = v.getId();