4

我创建了一个ImageView

ImageView _view;
ViewGroup _root;
public void CreateImageView() {
    _root = (ViewGroup) findViewById(R.id.root);
    for (int i = 0; i < 5; i++) {
        _view = new ImageView(this);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(100, 100);
        layoutParams.leftMargin = 150;
        layoutParams.topMargin = 50;
        _view.setLayoutParams(layoutParams);
        _view.setId(i);
        _root.addView(_view);
    }
}

当我单击 id = 3 的图像视图时,应该调用一个 Toast。我怎样才能做到这一点?

4

3 回答 3

5

取一个整型的 imageview 数组,_view = new ImageView[size];并在forloopinitialize 中设置标签为 imageview,然后在处理点击事件时,像这样获取标签,int k = (Integer) v.getTag();这样你就可以准确地点击你的视图。

ImageView _view;
      ViewGroup _root;
      public void CreateImageView()
      {
          _root = (ViewGroup)findViewById(R.id.root);
_view = new ImageView[5];
            for ( int i = 0; i< 5;i++)
            {
                _view[i] = new RadioButton(this);
                _view[i].setTag(i);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(100, 100);
                layoutParams.leftMargin = 150;
                layoutParams.topMargin = 50;
                _view.setLayoutParams(layoutParams);
                _root.addView(_view[i]);
            }
      }

点击事件#

 _view[j].setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub.
    int k = (Integer) v.getTag();

        if(k==3){
        Toast.makeText(this, "Your Message", Toast.LENGTH_LONG).show();
      }

    }
 }
于 2012-11-27T05:10:13.440 回答
3

当我单击 imageview id = 3 时,将调用 Toast.maketext 我该怎么做?

将这样的内容添加到您的循环中:

if(i == 3) {
    _view.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "Message", Toast.LENGTH_LONG).show();
        }
    });
}
于 2012-11-27T05:03:30.333 回答
1

不确定您到底想达到什么目的。但是您可以尝试以下代码段。

ImageView imgView = (ImageView) _root.findViewById(3);

imgView.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Hello World from image 3",
        Toast.LENGTH_SHORT).show();

    }
});
于 2012-11-27T05:23:31.387 回答