【发布时间】:2015-02-03 10:43:03
【问题描述】:
我有 2 种口味 - 付费应用和免费应用。
支付应用程序的唯一区别是在MainActivity 上多了 1 个按钮,比如"paidbutton"。
付费应用有自己的布局,带有按钮android:id="@+id/paidbutton",而免费应用的布局没有这个按钮。
在代码中我使用这个:
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); 中有错误cannot find symbol variable
如何在不克隆两种风格的 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>
/app/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(getIdFromRId("paidbutton"));代替View paidbutton = findViewById(R.id.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;
}
【问题讨论】:
-
面临同样的错误,但这似乎是预期的行为,因为当我们切换到特定的
build variant(flavor)时,会加载特定类型的资源,因此 IDE 会给出错误找不到符号。您有两个选项 1. 要么将两个按钮都放在 activity_main 中,然后使用 main 中的一个布局文件(不需要特定于风味的版本),然后在运行时根据风味的基础隐藏/显示按钮。 2. 在两种口味中复制您的MainActivity.java!
标签: android r.java-file android-productflavors