我想动态添加带控件的布局,将来我想将这些数据保存到DB。
public void onClickAdd(View view) {
LayoutInflater ltInflater = getLayoutInflater();
final LinearLayout subLayoutFields = (LinearLayout) findViewById(R.id.subLayoutFields);
LinearLayout subLayoutFields1;
final View view1 = ltInflater.inflate(R.layout.sub_fields, subLayoutFields, true);
subLayoutFields.setId(countID);
countID++;
}
编译器没有成功完成。这有什么问题?我在
上出错了subLayoutFields.setId(countID);
错误是:
报告两类问题:提供错误类型的资源 标识符。例如,当您调用Resources.getString(int id)时 应该传递R.string.something,而不是R.drawable.something。 将错误的常量传递给期望其中一个特定的方法 常量集。例如,在调用View#setLayoutDirection时, 参数必须是android.view.View.LAYOUT_DIRECTION_LTR或 android.view.View.LAYOUT_DIRECTION_RTL
谢谢...
答案 0 :(得分:0)
喜欢这个
someView.setId(GenerateViewId.generateId());
这是您需要的UTIL
import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;
import java.util.concurrent.atomic.AtomicInteger;
public class GenerateViewId {
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
/**
* Generate a value suitable for use in setId(int}.
* This value will not collide with ID values generated at build time by aapt for R.id.
*
* @return a generated ID value
*/
private static int generateViewId() {
for (; ; ) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) {
newValue = 1; // Roll over to 1, not 0.
}
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
@SuppressLint("NewApi")
public static int generateId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return generateViewId();
}
else {
return View.generateViewId();
}
}
}