我有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