如何在布局中识别视图?

时间:2012-11-27 04:57:23

标签: android view relativelayout

我创建了一个 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的imageview时,应该调用Toast。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:5)

获取像_view = new ImageView[size];这样的整数图像视图,并在forloop内初始化并将标记设置为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();
      }

    }
 }

答案 1 :(得分: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();
        }
    });
}

答案 2 :(得分: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();

    }
});