XAMARIN: как найти ViewById <TabWidget>??? (Ресурс не найден) - PullRequest
0 голосов
/ 30 октября 2018

Я получаю сообщение об ошибке "ресурс не найден" при попытке сделать это:

    TabWidget tabz = FindViewById<TabWidget>(Resource.Id.tabs);

компилятор не видит TabWidget, даже если он четко обозначен идентификатором в моем файле Main.axml

Ошибка CS0117 «Resource.Id» не содержит определения для «вкладок»

Вот мой полный код:

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
    android:id="@android:id/tabs"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:visibility="visible" />
<FrameLayout
    android:id="@android:id/tabcontent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp" />
</LinearLayout>

РЕДАКТИРОВАТЬ, извините, это полный код ... Я не знаю, почему я не копировал это в прошлый раз. В приведенном выше примере отсутствует TabHost

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TabHost
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minWidth="25px"
        android:minHeight="25px"
        android:id="@+id/tabHost1">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:id="@+id/linearLayout1">
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </TabHost>

</LinearLayout>

Как заставить компилятор распознавать мой идентификатор вкладки? Я попытался пересобрать resource.designer.cs .. поместить объявление TabWidget во все действия ... ничего не работает. Мой C # не видит TabWidget

Полный проект можно найти здесь:

https://github.com/hexag0d/BitChute_Mobile_Android_a2

Я тоже попробовал это, и это не сработало Файл ресурсов Android Xamarin не найден

спасибо, заранее

Ответы [ 2 ]

0 голосов
/ 31 октября 2018

Проблема не в компиляторе Visual Studio, а в том, как вы объявили идентификатор для своего View,

Если вы проверите этот блог Джеймса Уайта, вы увидите, как Id и Layout атрибуты действительно работают в Android,

Правильный способ объявления Id был бы примерно таким android:id="@+id/tabs", тогда как то, что вы делаете, это android:id="@android:id/tabs"

Следовательно, когда вы добавляете их и пытаетесь найти их с помощью Resource.Id.tabs, в идентификаторе нет ничего доступного в закладках с именами, поскольку оно никогда не добавлялось файлом Xamarin ResourceDesginer.cs.

Таким образом, конечный результат должен быть примерно таким:

  <TabHost
    android:id="@+id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:id="@+id/tab1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#ffc916"
                android:orientation="vertical">
        </LinearLayout>
        </FrameLayout>
    </LinearLayout>
  </TabHost>

Кроме того, обратите внимание, что я заменил все fill_parent на match_parent, причина в том, что заполнение родительского элемента теперь устарело, или вы можете сказать, заменено (после API-8) и, следовательно, не должно быть используется, который можно найти здесь .

Обновление:

Я обновил способ работы хоста вкладок, также обновил XML выше и добавляю справочную ссылку , где вы можете найти правильный способ использования TabHost и TabWidget, также хороший SO пример для того же.

0 голосов
/ 30 октября 2018

О вопросах в вашем комментарии:

1

это очень хороший совет, но одна нота в том, что когда SetContentView (localLayout); используется внутри деятельности, которая уже имеет представление содержимого, приложение вылетает.

Приложение упало, потому что localLayout в SetContentView (localLayout) является LinearLayout, но TabWidget требует TabHost. Таким образом, вы можете напрямую использовать:

SetContentView(Resource.Layout.Main);

где Main.xaml похож на:

<?xml version="1.0" encoding="utf-8"?>

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:theme="@style/MyTheme">

   <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.0"
        android:visibility="visible" />
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" />
    </LinearLayout>
</TabHost>

2

LinearLayout localLayout = FindViewById (Resource.Layout.Main); Посмотреть whichYouWantToUse_findViewById = LayoutInflater.Inflate (Resource.Layout.Main, null); TextView TV = FindViewById (Resource.Id.textView169); TabHost _tabHost = (TabHost) whichYouWantToUse_findViewById.FindViewById (Resource.Id.tabhost); 'до сих пор не вижу табхоста ... я схожу с ума здесь

Причина, по которой вы не видите tabhost, во-первых, TabHost - это FrameLayout, а не LinearLayout, во-вторых, Resource.Id.tabhost должен быть Android.Resource.Id.TabHost. Поэтому я отредактировал ваш код так:

    FrameLayout localLayout = FindViewById<FrameLayout>(Resource.Layout.Main);
    whichYouWantToUse_findViewById = LayoutInflater.Inflate(Resource.Layout.Main, null);
    //TextView tv = FindViewById<TextView>(Resource.Id.textView1);
    TabHost _tabHost = (TabHost)whichYouWantToUse_findViewById.FindViewById(Android.Resource.Id.TabHost);

3

Так что интересно, если я поменяю tabhost на tahost ala android: id = "@ + id / tahost" ресурс появляется в конструкторе, но когда Я меняю на андроид: id = "@ + id / tabhost" ресурс исчезает .. очень странно ..

Идентификатор TabHost всегда должен быть @android: id / tabhost ", его нельзя изменить на tahost или любой другой.

Итак, код в методе onCreat выглядит следующим образом:

    base.OnCreate(bundle);

    SetContentView(Resource.Layout.Main);
    View whichYouWantToUse_findViewById = LayoutInflater.Inflate(Resource.Layout.layout1, null);
    TextView textInAnotherLayout = (TextView)whichYouWantToUse_findViewById.FindViewById(Resource.Id.textView1);
    textInAnotherLayout.Text = "Yeah";

    TabHost tabHost = FindViewById<TabHost>(Android.Resource.Id.TabHost);
    TabWidget tabWidget = tabHost.TabWidget;
    var tabContent = tabHost.TabContentView;

    FrameLayout localLayout = FindViewById<FrameLayout>(Resource.Layout.Main);
    whichYouWantToUse_findViewById = LayoutInflater.Inflate(Resource.Layout.Main, null);
    TabHost _tabHost = (TabHost)whichYouWantToUse_findViewById.FindViewById(Android.Resource.Id.TabHost);

Вот старый ответ.


Ответ изменен: способ получить TabHost и TabWidget в Activity:

TabHost tabHost = this.TabHost;
TabWidget tabWidget = tabHost.TabWidget;

Способ использования одного ресурса из одного файла XAML в упражнении для другой:

    LinearLayout localLayout = FindViewById<LinearLayout>(Resource.Layout.Main);
    SetContentView(localLayout);
    View whichYouWantToUse_findViewById = LayoutInflater.Inflate(Resource.Layout.layout1, null);
    Button button1 = (Button)whichYouWantToUse_findViewById.FindViewById(Resource.Id.button1);

Я загружаю ваш проект и исправляю эту проблему, изменяя свойство> android: id

...