1

我已经实现了 Horizo​​ntalScrollView 来显示图像。但我无法找到实现 onclick 侦听器的方法,以便在 Horizo​​ntalScrollView 上单击特定图像。

我已经在 imageview 1 上实现了 onclick,我也在调用 imageview 期间设置了 ID,但在 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();
                }
            });
4

1 回答 1

1

您想获取刚刚单击的视图的 id,而不是循环中创建的最后一个视图。因此,只需将 OnClickListener 中的变量从iv

int s =iv.getId();

v,视图传递给onClick()

int s = v.getId();
于 2012-11-06T17:20:49.640 回答