Tôi nhận được ngoại lệ con trỏ rỗng trong chế độ xem tùy chỉnh của mình (được bắt nguồn từ LinearLayout
) vì không thể tìm thấy chế độ xem con. Đây là mã:Bố trí không bị phồng lên trong thành phần tùy chỉnh android
public class MyView extends LinearLayout
{
public MyView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
private TextView mText;
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
mText = (TextView) findViewById(R.id.text);
if (isInEditMode())
{
mText.setText("Some example text.");
}
}
}
Dưới đây là cách bố trí (my_view.xml
):
<?xml version="1.0" encoding="utf-8"?>
<com.example.views.MyView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:ellipsize="end"
android:maxLines="4"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:text="Some text" />
</com.example.views.MyView>
Và đây là làm thế nào tôi đặt nó trong file XML:
<com.example.views.MyView
android:id="@+id/my_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Nhưng khi tôi cố gắng để xem trước nó trong trình chỉnh sửa bố cục, tôi nhận được NPE trên mText.setText(...)
vì getViewById()
trả về null
.
Điều gì đang xảy ra?
Làm rõ
Lý do tôi hy vọng điều này để làm việc, là nếu tôi làm
MyView v = (MyView)inflater.inflate(R.layout.my_view);
((TextView)v.findViewById(R.id.text)).setText("Foo");
tất cả mọi thứ hoạt động tốt. Đó không phải là những gì inflater bố trí hiện khi nó đi qua một tập tin bố trí? Trong mọi trường hợp, làm thế nào tôi có thể xử lý cả hai tình huống một cách chính xác (mà không nhận được quan điểm lồng nhau vô nghĩa)?
ở đâu ' 'a nd tại sao không phải là 'android: id' của bạn tuyên bố nơi bạn lần đầu tiên tuyên bố nó trong bố trí? –
codeMagic
Tôi không cần một id ở đó. – Timmmm