Tôi không thể hiểu tại sao findViewById trả về phần tử sai, đây là lớp:findViewById truy xuất phần tử sai?
public class EventDetailsFragment extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_details);
Log.d("First", findViewById(R.id.tuxtView1).getClass().toString());
Log.d("Second", findViewById(R.id.tuxtView2).getClass().toString());
Log.d("Third", findViewById(R.id.imageView1).getClass().toString());
}
}
Và đây là xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp">
<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="0dp"
android:layout_height="175dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:background="#fff"
android:gravity="right" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="110dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:src="@drawable/ic_event_image" />
<TextView
android:id="@+id/tuxtView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp" />
<TextView
android:id="@+id/tuxtView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tuxtView2"
android:layout_toRightOf="@+id/imageView1"
android:textColor="#555"
android:textSize="20dp" />
</RelativeLayout>
</LinearLayout>
Các ouput logcat là:
12-26 23:43:20.249: D/First(6789): class android.widget.TextView
12-26 23:43:20.249: D/Second(6789): class android.widget.ImageView
12-26 23:43:20.249: D/Third(6789): class android.widget.TextView
Vì vậy, vấn đề là, tại sao tôi nhận được một lần xem hình ảnh với id R.id.tuxtView2 và một lần xem văn bản với id R.id.imageView1. Ứng dụng bị treo nếu tôi muốn gán giá trị văn bản cho R.id.tuxtView2, được đúc dưới dạng TextView.
Hãy thử tải lại dự án của bạn, có thể đã xảy ra sự cố với R.java hoặc xác minh bạn đang gọi tệp tốt với setContentView. –
Câu hỏi được ghi lại đầy đủ. Xin lỗi, không biết tại sao điều này lại xảy ra. –
@ JeremyD, wow, tôi đã thử tất cả mọi thứ, trong một vài giờ, ngoại trừ khởi động lại nhật thực. Tôi khởi động lại nhật thực và nó đột nhiên làm việc trở lại. Tôi nghĩ rằng tôi đã làm điều gì đó sai trong mã của tôi. Đăng câu trả lời đó và tôi sẽ bình chọn cho bạn + đánh dấu nó là đã được giải quyết. Cảm ơn! – jonepatr