我将布局.xml文件转换为Java时遇到问题 我很喜欢尝试但未能完成。 我需要任何人帮助完成它。 需要帮忙!提前谢谢。
这是我的布局.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lay"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox_cheese"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cheese"
android:onClick="onCheckboxClicked"/>
</LinearLayout>
我只是想将它转换为我迄今为止尝试过的java:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.lay);
CheckBox box = new CheckBox(this);
box.setId(c);
/* from here how to convert those below lines in Java
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cheese"
android:onClick="onCheckboxClicked"
*/
答案 0 :(得分:1)
我心情很好,或者我只想指出你对叶戈尔的评论;这些教程旨在向您展示做您想做的事的有效方法。
LinearLayout.LayoutParams boxParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
box.setLayoutParams(boxParams);
box.setText(R.string.cheese);
// if you want checkbox change listener
box.setOnCheckedChangedListener(new OnCheckedChangedListener(){
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (isChecked){
// perform logic
}
}
};
// if you want on click listener functionality
box.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
// perform logic
}
}
linearLayout.addView(box);
Haven没有对它进行测试,也不知道它是否没有错误(可能错过了某些内容或做错了什么),但我可以告诉你,除非你打算只做这个功能而不是其他功能您真正需要阅读Android基础知识的功能。
答案 1 :(得分:0)
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- &GT; setLayoutParams(..)
android:text="@string/cheese"
- &GT;的setText(..)
android:onClick="onCheckboxClicked"
- &GT; setOnClickListener(..)
答案 2 :(得分:0)
做这样的事情:
View layout = ViewInflater.from(this).inflate(R.layout.layout, null); //your layout name
LinearLayout linearLayout = (LinearLayout) layout.findViewById(R.id.lay);
CheckBox box = (CheckBox) layout.findViewById(R.id.checkbox_cheese);
现在box
对象将在xml中分配所有属性。