Ошибка android.content.res.Resources$NotFoundException: файл из идентификатора ресурса макета типа xml # 0x102000a

Эй, я пытаюсь создать дизайн для списка, который выглядит (и в основном ведет себя как) журнал вызовов, как показано здесь:

альтернативный текст

Для этого я скачал исходный код и изучаю его, чтобы узнать, какой класс и xml-файл его реализуют.

И я нашел эти два XML-файла recent_calls_list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="?android:attr/listPreferredItemHeight"
android:paddingLeft="7dip"> 

<com.psyhclo.DontPressWithParentImageView
    android:id="@+id/call_icon" android:layout_width="wrap_content"
    android:layout_height="match_parent" android:paddingLeft="14dip"
    android:paddingRight="14dip" android:layout_alignParentRight="true"

    android:gravity="center_vertical" android:src="@android:drawable/sym_action_call"
    android:background="@drawable/call_background" />

<include layout="@layout/recent_calls_list_item_layout" />

and the other is recent_calls_list_item_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

<View android:id="@+id/divider"
    android:layout_width="1px"
    android:layout_height="match_parent"
    android:layout_marginTop="5dip"
    android:layout_marginBottom="5dip"
    android:layout_toLeftOf="@id/call_icon"
    android:layout_marginLeft="11dip"
    android:background="@drawable/divider_vertical_dark"
/>

<ImageView android:id="@+id/call_type_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="4dip"
/>

<TextView android:id="@+id/date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/divider"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="8dip"
    android:layout_marginLeft="10dip"

    android:textAppearance="?android:attr/textAppearanceSmall"
    android:singleLine="true"
/>

<TextView android:id="@+id/label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="36dip"
    android:layout_marginRight="5dip"
    android:layout_alignBaseline="@id/date"

    android:singleLine="true"
    android:ellipsize="marquee"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:textStyle="bold"
/>

<TextView android:id="@+id/number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/label"
    android:layout_toLeftOf="@id/date"
    android:layout_alignBaseline="@id/label"
    android:layout_alignWithParentIfMissing="true"

    android:singleLine="true"
    android:ellipsize="marquee"
    android:textAppearance="?android:attr/textAppearanceSmall"
/>

<TextView android:id="@+id/line1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@id/divider"
    android:layout_above="@id/date"
    android:layout_alignWithParentIfMissing="true"
    android:layout_marginLeft="36dip"
    android:layout_marginBottom="-10dip"

    android:textAppearance="?android:attr/textAppearanceLarge"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:gravity="center_vertical"
/>

And my activity is this:

public class RatedCalls extends ListActivity {

private static final String LOG_TAG = "RecentCallsList";
private TableLayout table;
private CallDataHelper cdh;
private TableRow row;
private TableRow row2;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.recent_calls_list_item);
    Log.i(LOG_TAG, "calling from onCreate()");

    cdh = new CallDataHelper(this);
    table = new TableLayout(getApplicationContext());
    row = new TableRow(getApplicationContext());

    startService(new Intent(this, RatedCallsService.class));
    Log.i(LOG_TAG, "Service called.");
    fillList();

}

public void onResume() {

    super.onResume();
    fillList();

}

public void fillList() {

    List<String> ratedCalls = new ArrayList<String>();
    ratedCalls = this.cdh.selectTopCalls();

    setListAdapter(new ArrayAdapter<String>(RatedCalls.this,
            android.R.id.list, ratedCalls));

    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Toast.makeText(getApplicationContext(),
                    ((TextView) view).getText(), Toast.LENGTH_LONG).show();
        }
    });

}

}

А потом я попытался запустить его на эмуляторе андроида, и тогда LogCat выдал такую ​​​​ошибку:

Вызвано: java.lang.RuntimeException: ваш контент должен иметь ListView, атрибут id которого равен «android.R.id.list».

Итак, внутри recent_calls_list_item.xml я объявил следующее:

<ListView android:id="@android:id/list" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:layout_x="1px"
    android:layout_y="1px">
</ListView>

И теперь с этим объявленным я попытался запустить в эмуляторе, но LogCat выдает другую ошибку:

android.content.res.Resources$NotFoundException: файл из идентификатора ресурса макета типа xml # 0x102000a

Итак, мой вопрос: почему это происходит? И если у вас есть другое решение для реализации такого представления, я попробую.

Спасибо.


person rogcg    schedule 11.01.2011    source источник


Ответы (7)


установите идентификатор вашего спискаView на

android:id="@id/android:list"

не знаю, то ли

android:id="@android:id/list"

работает правильно

person Jonathan Roth    schedule 11.01.2011

У меня такая же проблема. Я устанавливал текст следующим образом:

statusView.setText(firstVisiblePosition);

Проблема заключалась в том, что firstVisiblePosition было целым числом. Компилятор не жаловался. Исправил это

statusView.setText(""+firstVisiblePosition);
person ile    schedule 30.10.2011
comment
спасибо, у меня была точно такая же проблема. Я нахожу исключение очень плохим, ничто не указывает на ошибку. - person pdiddy; 30.11.2011
comment
Все ресурсы отображаются как целые числа в Android (в R.java), поэтому метод setText считает, что вы ссылаетесь на строковый ресурс (тот, который не существует). - person Josh Clemm; 10.05.2012
comment
Более чистый способ сделать это будет statusView.setText(String.valueOf(firstVisiblePosition)); - person howettl; 11.05.2012
comment
Не объединяйте пустые строки - person m0skit0; 02.10.2012
comment
это правильный ответ, ребята. но эта ошибка очень странная. почему settext должен начинаться со строки? вместо прямой переменной. - person Yogamurthy; 02.12.2014

Звучит неубедительно, но если вы используете Eclipse, пробовали ли вы очищать и перестраивать свой проект? Это устранило аналогичную проблему, с которой я столкнулся.

person anisbet    schedule 03.08.2011

Я также могу решить проблему, преобразовав значение Integer в String при использовании:

name.setText(name_value_needs_to_be_string);

где имя — TextView.

person Khushboo    schedule 08.02.2012

Компилятор интерпретирует ваш аргумент int как ссылку на ресурс и предполагает, что вы вызываете:

 public final void setText (int resourceId)

но ты собирался позвонить

 public final void setText (CharSequence text)

Чтобы исправить это, сделайте так:

myTextView.setText(Integer.toString(myIntegerValue));
person onosendai    schedule 14.11.2013

Я решил эту проблему, скопировав файл XML из каталога layout-land в каталог layout (или наоборот). На некоторых устройствах по умолчанию установлен альбомный режим, на других — портретный. Если этот файл не существует в этом режиме, выдается это исключение.

person mrek    schedule 30.07.2015

В моем случае просто какой-то идентификатор в моем xml был неправильным. Проверьте свои идентификаторы в своих макетах

Ссылка на ошибку:

app:layout_constraintBottom_toBottomOf=@id/loginЭлектронная почта

Реальная ссылка:

app:layout_constraintBottom_toBottomOf=@id/loginEmailEntryCode

person Miguel Bogarin    schedule 10.03.2021