简体   繁体   中英

Is there any solution to use only 1 findViewById in different methods

I have 2 different methods.

Method a will display textview1. Method b will also display textview1.

In both the methods, I need to include findViewById(R.id.textview1). Thus need to put twice findViewById in the code.

// if you are using Kotlin, apply this plugin with the kotlin library in your app Module Gradle

apply plugin: 'kotlin-kapt'

kapt {
    generateStubs = true
}

// then you can just give the name of the view in the XML layout and you dont have to initialize the view eg ..

// xml view

<TextView
                        android:id="@+id/tv_location"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"

                        android:gravity="center_vertical"
                        android:paddingStart="8dp"
                        android:singleLine="true"

                        android:textSize="14sp" />

// now in the kotlin class

tv_location.text = "Kolkata,India" 

//try this 

Use butterknife library:

class Activity {
    @BindView(R.id.textview1)
    TextView view1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
    }

You can now access view1 in any methods in this activity.

You can declare your textview as global variable. Then you can use that variable anywhere in that activity or class or fragment.

public class Main2Activity extends AppCompatActivity {

   private TextView textView1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);
      textView1 = findViewById(R.id.textview1);
   }
   private void method1(){
      textView1.setText("method 1");
   }
   private void method2(){
      textView1.setText("method 2");
   }
}

ButterKnife is developed by Jake Wharton at Square and is essentially used to save typing repetitive lines of code like findViewById(R.id.view) when dealing with views, thus making our code look a lot cleaner.

add this dependency into your build.gradle

compile 'com.jakewharton:butterknife:6.1.0'

write this on onCreate()

ButterKnife.bind(this);

and than you can find you elements like this :

@Bind(R.id.txtview1)
Textview textview;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM