開發語言的進步,感觸最新的就是,以前寫windows的時候使用的是C#後來,學習了一下WPF,內心就是感慨萬千
居然用xml來寫界面了,不用那些抽象的代碼來寫,關鍵是xml的界面具有實時性、可觀性。xml就和html一樣,標記語言。
可以直接在瀏覽器看到。
之後學習Android後,感覺又回來,真的,語言在進步呀。
在Android中xml時如何連接到java的呢?
是這樣的:
value中新建一個atrrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DivActionBar">
<attr name="right_onclick" format="string" />
</declare-styleable>
</resources>
xml中引用:
使用空間名:
xmlns:app=”http://schemas.android.com/apk/res/com.tuxiaobei“
使用
app:right_οnclick="function"
java中映射關聯:
TypedArray array = context
.obtainStyledAttributes(attrs, R.styleable.DivActionBar);
final String methodName;
methodName = array.getString(R.styleable.DivActionBar_right_onclick);
rightText.setOnClickListener(new OnClickListener() {
private Method method;
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(methodName)) {
if (method == null) {
try {
method = getContext().getClass().getMethod(methodName,
DivActionBar.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find a method "
+ method + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + DivActionBar.this.getClass() + e);
}
try {
method.invoke(getContext(), DivActionBar.this);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
});
關鍵是:method = getContext().getClass().getMethod(methodName,DivActionBar.class)
對於項目的還是不要在xml中寫點擊事件,畢竟是有點性能嫌疑滴。