![](/img/trans.png)
[英]Unable to get data in view using data-binding in custom dialog - Android
[英]Data Binding in Android Custom View
我已經創建了一個自定義布局,如下所示。 我想用這個布局執行數據綁定。 我該如何執行此任務。
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:id="@+id/no_internetConnection_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_toRightOf="@+id/icon_noInternet_connection"
android:text="@string/no_Internet_Connection_text" />
</LinearLayout>
</layout>
這是現有的代碼。 如何用數據綁定代碼替換現有代碼。
public class NetworkConnectionCheck {
private Context _context;
public NetworkConnectionCheck(Context _context) {
this._context = _context;
}
public void CustomToastShow() {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate( R.layout.customtoast, null );
TextView text = (TextView) view.findViewById(R.id.no_internetConnection_Text);
ImageView imageView = (ImageView) view.findViewById(R.id.icon_noInternet_connection);
Toast toast = new Toast(_context);
toast.setGravity(Gravity.BOTTOM|Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
toast.show();
}
}
目前我收到一個錯誤。 這是因為布局標簽。
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class layout
你需要添加
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<merge>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:id="@+id/no_internetConnection_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_toRightOf="@+id/icon_noInternet_connection"
android:text="@string/no_Internet_Connection_text" />
</LinearLayout>
<merge/>
</layout>
並在您的自定義視圖中
public class NetworkConnectionCheck {
private Context context;
public NetworkConnectionCheck(Context context) {
super(context);
init();
}
public NetworkConnectionCheck(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public NetworkConnectionCheck(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void CustomToastShow() {
binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.customtoast, this, true);
//do what you need to do with the binding
}
}
我希望您已經在模塊gradle文件中啟用了dataBinding。
android {
....
dataBinding {
enabled = true
}
}
未生成MyLayoutBinding,因為您的xml文件不包含數據標記。 將數據標記放在布局中並在數據內部聲明變量后,應生成MyLayoutBinding
對於遇到相同問題的其他人,請檢查以下內容:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.