当我尝试以编程方式添加textview时,我无法设置setOnFocusChangeListener
甚至setOnClickListener
。
我试过
txt1.requestFocus();
txt1.setFocusable(true);
txt1.setFocusableInTouchMode(true);
和
txt1.setClickable(true);
setOnTouchListener
正在运作,但其他听众却没有。
这是我的代码:
text_b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
try
{
TextView txt1 = new TextView(DashActivity.this);
txt1.setText("This is me");
txt1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
txt1.setTextColor(Color.parseColor("#FAC421"));
txt1.requestFocus();
txt1.setFocusable(true);
txt1.setFocusableInTouchMode(true);
txt1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
try
{
Log.i("txt: ", "Clicked");
}
catch (NullPointerException e)
{
e.printStackTrace();
}
}
});
txt1.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, boolean hasFocus)
{
Log.i("txt:" , "Changed");
if(hasFocus)
{
v.setBackgroundResource(R.drawable.text_border);
}
else
{
v.setBackgroundResource(0);
}
}
});
txt1.setOnTouchListener(new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
// Offsets are for centering the TextView on the touch location
v.setX(event.getRawX());
v.setY(event.getRawY());
}
return true;
}
});
mRrootLayout.addView(txt1);
}
catch (NullPointerException e)
{
e.printStackTrace();
}
}
});
任何解决方案?
答案 0 :(得分:0)
在false
的{{1}}方法中返回true
而不是onTouch
。当您返回true时,将此触摸事件标记为已处理,因此此触摸事件不会进一步传播(到OnClickListener和OnFocusChangeListener)。