3

Android XML レイアウト ファイルで 2 つのビュー間の関係を指定したいと考えています。これが私がやりたいことです:

 <View
      android:id="@+id/pathview"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
  ...
  <CheckBox
      android:id="@+id/viewPath"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:checked="true"
      android:paddingRight="7dp"
      android:shadowColor="#000000"
      android:shadowDx="0.5"
      android:shadowDy="0.5"
      android:shadowRadius="0.5"
      android:tag="@id/pathview"
      android:text="Paths" />

ただし、XML パーサーはタグを文字列として扱い、整数として解釈しません ( System.out.println((String) [viewPath].getTag());"false" が表示されます)。ビューのタグにリソース ID を割り当てる方法はありますか?

4

2 に答える 2

2

使用する場合

android:tag="?id/pathview" 

疑問符が前に付いた 10 進整数として文字列 ID を取得します。この動作に関するドキュメントは見つかりませんが、十分に安定しているようです。あなたがしているのは、現在のテーマの ID を要求することです。結果の文字列の前に「?」が付くのはなぜですか? は不明です。

例えば:

何らかの識別子が与えられると、

public static final int test_id=0x7f080012;

やって、

android:tag="?id/test_id"

タグ値になります。

"?2131230738"

その後、次のことができます。

 View otherView = activity.findViewById(
    Integer.parseInt(
        someView.getTag().toString().substring(1)
    )
 );

もちろん、より一般化されたロジックを記述している場合は、null のタグをチェックして NumberFormatException をキャッチする必要があります。

于 2013-05-27T20:19:50.857 に答える
1

id 文字列をタグとして設定し、id を取得できます。

いくつかのような:

<View
  android:id="@+id/pathview"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />
...
<CheckBox
  android:id="@+id/viewPath"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:checked="true"
  android:paddingRight="7dp"
  android:shadowColor="#000000"
  android:shadowDx="0.5"
  android:shadowDy="0.5"
  android:shadowRadius="0.5"
  android:tag="pathview"
  android:text="Paths" />

次に、コードで:

CheckBox viewPath = findViewById(R.id.pathview);
String pathViewStrId = (String) viewPath.getTag();
int patViewId = getResources().getIdentifier(pathViewStrId, "id", getPackageName());
View pathView = findViewById(patViewId);
于 2012-11-16T20:39:11.013 に答える