如何在android中获取动态创建的View的ID?实际上我的布局中有很多视图,我希望用户触摸该视图的id。有可能吗?如果是的话比怎么做?
在下面的代码中创建了新的Frame Layout,我为此布局生成了ViewId,并将此id保存为HashMap的关键字(logoResizingRecordList)。
FrameLayout fm=new FrameLayout(getApplication());
FrameLayout.LayoutParams params=new FrameLayout.LayoutParams(400,300);
fm.addView(img_pinch,params);
int FrameLayoutID=fm.generateViewId();
logoResizingRecordList.put(FrameLayoutID,logoObj);
fm.setOnTouchListener(logoTouchListner);
这里OnTouch我已经将FrameLayout的实例分配给temp_img_logo。
public boolean onTouch(final View p_v, MotionEvent p_event)
{
if(p_v instanceof FrameLayout) {
temp_img_logo=(FrameLayout)p_v;
}
这里我想得到上面FrameLayout(fm)的id但它返回任何View的默认Id,即-1
logoResizingRecordList.get(temp_img_logo.getId())
现在我的问题是,是否有可能获得我动态创建的fm(FrameLayout)的id?如果是,那么请帮我找到它。
答案 0 :(得分:0)
将所有这些的onclick侦听器设置为单个侦听器,并切换onclick方法的arg1.getId()
答案 1 :(得分:0)
是的,你可以,
首先,为了获得id,你必须设置id,
TextView txt = new TextView(context);
txt.setId(some integer);
然后你必须在像数组或列表这样的地方保留动态视图。 然后您可以获得被触摸的位置并获得相关的视图ID,如下所示,
int id = textViewList.get(position).getId();
答案 2 :(得分:0)
Android不会动态生成ID。你必须自己做。
一个可以帮助您的简单示例:
public static final int TEXT_VIEW1_ID = 1001;
TextView textView1 = new TextView(Context);
textView1.setId(TEXT_VIEW1_ID);
relativeLayout.addView(textView1);
relativeLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if(view.getId() == TEXT_VIEW1_ID){
Toast.makeText(context, "TextView1 was touched.", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});