我有2種風格 - paidapp和freeapp。 付款應用程序在MainActivity
上有另外1個按鈕,比如"paidbutton"
。 paidapp有自己的按鈕android:id="@+id/paidbutton"
佈局和freeapp的佈局沒有這個按鈕。Android風味 - 在R文件中找不到符號變量
在代碼中我使用這個:
if (BuildConfig.FLAVOR.equals("paidapp")) {
View paidbutton = findViewById(R.id.paidbutton);
paidbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//...
}
});
}
但我cannot find symbol variable
在findViewById(R.id.paidbutton);
錯誤如何在沒有在這兩種口味克隆MainActivity.java解決這個問題?
EDIT1 - 添加更多的代碼實例:
搖籃:
productFlavors {
paidapp {
}
freeapp {
}
}
/app/src/main/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/goNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go next" />
</LinearLayout>
/應用/ src/paidapp/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/goNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go next" />
<Button
android:id="@+id/paidbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="See more" />
</LinearLayout>
/app/src/main/java/company/com/myapplication/MainActivity.java
package company.com.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View goNext = findViewById(R.id.goNext);
goNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "goNext click", Toast.LENGTH_SHORT).show();
}
});
if (BuildConfig.FLAVOR.equals("paidapp")) {
View paidbutton = findViewById(R.id.paidbutton);
paidbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "paidapp click", Toast.LENGTH_SHORT).show();
}
});
}
}
}
EDIT2 - 我已經找到了一些解決方法使用反射,但仍然在尋找正解:
的代替View paidbutton = findViewById(R.id.paidbutton);
我用View paidbutton = findViewById(getIdFromRId("paidbutton"));
其中getIdFromRId
是:
private int getIdFromRId(String idName) {
int id = 0;
try {
Class c = R.id.class;
Field field = c.getField(idName);
id = field.getInt(null);
} catch (Exception e) {
// do nothing
}
return id;
}
面對相同的錯誤,但這似乎是預期的行爲,因爲當我們切換到特定的'構建變體(flavor)'時,該特定的資源被加載,因此IDE給出錯誤找不到符號。你有**兩個選項** 1.或者你把兩個按鈕都放在activity_main中,並且使用main中的一個佈局文件(不需要特定於風味的版本)並且在運行時基於風味隱藏/顯示按鈕。 2.將你的'MainActivity.java'複製到兩種口味中! – 2016-03-11 10:23:37