Reputation: 19
I am facing problem to convert layout .xml files to Java I fave tried but failed to complete. I need anyones help to complete it. Need Help! Thanks in advance.
Here is my layout .xml file:
<?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>
I just want to convert it to java which i have tried so far:
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"
*/
Upvotes: 0
Views: 74
Reputation: 3389
I am in a good mood, or I would have just pointed you to Egor's comment; the tutorials are designed to show you the efficient ways to do what you want.
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't tested it, don't know if it is bug free (may have missed something or done something wrong), but I can tell you that unless you plan on only doing this functionality and no other functionality you REALLY need to read into the basics of Android.
Upvotes: 1
Reputation: 7082
Do something like this:
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);
Now the box
object will have all the properties assigned in the xml.
Upvotes: 0
Reputation: 39519
android:layout_width="wrap_content"
android:layout_height="wrap_content"
->setLayoutParams(..)
android:text="@string/cheese"
->setText(..)
android:onClick="onCheckboxClicked"
->setOnClickListener(..)
Upvotes: 0