findViewById(); with a variable within the method

Asked

Viewed 2,562 times

0

Kind of:

public void main(){
  String a = "bt1";   
  Button bt1 = (Button) findViewById(R.id.a);   
}

I know it doesn’t work, but it would be something like this, using a variable String.

  • Your goal is to get a View based on your name ? In other words, in the String representing the id ?

1 answer

3


No, it is not possible. It is necessary to pass the ID (which is a int), to capture the View through the method findViewById, but you can use a similar method.

With the findViewWithTag you can capture the view who possess a tag.

Just add the attribute android:tag="custom" in his view. Ex:

Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/viewPrincipal">

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="148dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:text="@string/btn_login"
        android:tag="tagDaView" <!-- Sua Tag -->
        android:theme="@android:style/Theme.Material.Light"
        android:background="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</android.support.constraint.ConstraintLayout>

Java:

String tag = "tagDaView";

View viewPrincipal = findViewById(R.id.viewPrincipal);
Button button = viewPrincipal.findViewWithTag( tag );

System.out.println( button.getText() );
  • It helped me a lot.... Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.