我有两种口味 – paidapp和freeapp.
唯一的区别是,paidapp在MainActivity上还有一个按钮,比如说“付费按钮”.
paidapp有自己的布局,按钮
android:id =“@ id / paidbutton”,freeapp的布局没有这个按钮.
在代码我用这个:
if (BuildConfig.FLAVOR.equals("paidapp")) {
View paidbutton = findViewById(R.id.paidbutton);
paidbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//...
}
});
}
但我有一个错误找不到findViewById(R.id.paidbutton)中的符号变量;
如何在不克隆MainActivity.java的情况下解决这个问题?
EDIT1 – 添加更多代码示例:
摇篮:
productFlavors {
paidapp {
}
freeapp {
}
}
/app/src/main/res/layout/activity_main.xml
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/goNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go next" />
/app/src/paidapp/res/layout/activity_main.xml
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/goNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go next" />
android:id="@+id/paidbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="See more" />
/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;
}