AppCompatActivity怎么对View做的拦截中分析了AppCompatActivity是怎么对View做拦截的。只需要在setContentView
方法之前设置下factory就可以了
public class MainActivity extends Activity {
@ViewById(R.id.textView)
TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewUtils.inject(this);
LayoutInflater layoutInflater = LayoutInflater.from(this);
LayoutInflaterCompat.setFactory2(layoutInflater, new LayoutInflater.Factory2() {
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
if ("TextView".equals(name)){
Button button=new Button(MainActivity.this);
button.setText("button");
return button;
}
return null;
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return null;
}
});
setContentView(R.layout.activity_main);
}
将页面内的TextView
控件替换为Button。
设置factory-->setContentView(内部执行LayoutInflater.inflate-->有设置factory回调factory的onCreateView方法)-->回调LayoutInflaterCompat.setFactory2中重写的onCreateView方法,完成View拦截和替换
运行截图
网友评论