findViewById (); with a variable within the method

0

Type like this:

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

I know this does not work, but it would be more or less like this, using a String variable.

    
asked by anonymous 12.02.2018 / 02:51

1 answer

2

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

With findViewWithTag you can capture the view that has tag .

Just add the android:tag="custom" attribute to your 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() );
    
12.02.2018 / 05:01