[英]Is there any solution to use only 1 findViewById in different methods
我有兩種不同的方法。
方法a 將顯示textview1。 方法 b 也會顯示 textview1。
在這兩種方法中,我都需要包含 findViewById(R.id.textview1)。 因此需要在代碼中放置兩次 findViewById。
// 如果您使用的是 Kotlin,請在您的應用模塊 Gradle 中將此插件與 kotlin 庫一起應用
apply plugin: 'kotlin-kapt'
kapt {
generateStubs = true
}
// 然后你可以在 XML 布局中給出視圖的名稱,而不必初始化視圖,例如 ..
// xml 視圖
<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" />
// 現在在 kotlin 類中
tv_location.text = "Kolkata,India"
//try this
使用黃油刀庫:
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);
}
您現在可以在此活動中以任何方法訪問view1
。
您可以將 textview 聲明為全局變量。 然后您可以在該活動或類或片段中的任何位置使用該變量。
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 由 Square 的 Jake Wharton 開發,主要用於在處理視圖時避免輸入重復的代碼行,例如 findViewById(R.id.view),從而使我們的代碼看起來更簡潔。
將此依賴項添加到您的 build.gradle 中
compile 'com.jakewharton:butterknife:6.1.0'
在 onCreate() 上寫這個
ButterKnife.bind(this);
然后你可以找到這樣的元素:
@Bind(R.id.txtview1)
Textview textview;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.