I am trying to create custom RadioButton/CheckBox as shown in image below.
I can also create image backgrounds for each of the button to make it look like this, but I don't think that's the only way.
I tried applying changes in XML layout with attributes like android:drawableLeft
, android:drawableRight
, android:drawableTop
, android:drawableBottom
, but not able to get the desired results.
Also found the same question with accepted answer but not the implementation.
I created a CustomRadioButton
class as well but it's not rendering anything.
CustomRadioButton.java
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.CardView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.app.togo.R;
/**
* Created by Darshan on 07-02-2018.
*
* @author Darshan Parikh (parikhdarshan36@gmail.com)
*/
public class CustomRadioButton extends AppCompatRadioButton {
String rbText;
boolean rbIsChecked;
int rbImageResource;
CheckBox checkBox;
public CustomRadioButton(Context context) {
super(context);
init(null);
}
public CustomRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomRadioButton);
rbText = a.getString(R.styleable.CustomRadioButton_rb_text);
rbIsChecked = a.getBoolean(R.styleable.CustomRadioButton_rb_isChecked, true);
rbImageResource = a.getResourceId(R.styleable.CustomRadioButton_rb_imgSrc, R.drawable.ic_car_clr);
a.recycle();
} else {
rbText = getRBText();
rbIsChecked = getRBIsChecked();
rbImageResource = getRBImageResource();
}
setText("");
setButtonDrawable(android.R.color.transparent);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.layout_custom_checkbox, null);
CardView cardView = (CardView) view;
RelativeLayout rootLayout = (RelativeLayout) cardView.getChildAt(0);
ImageView imageView = (ImageView) rootLayout.getChildAt(0);
TextView textView = (TextView) rootLayout.getChildAt(1);
checkBox = (CheckBox) rootLayout.getChildAt(2);
imageView.setImageResource(rbImageResource);
textView.setText(rbText);
checkBox.setChecked(rbIsChecked);
}
public String getRBText() {
return rbText;
}
public boolean getRBIsChecked() {
return rbIsChecked;
}
public int getRBImageResource() {
return rbImageResource;
}
@Override
public void toggle() {
super.toggle();
checkBox.setChecked(isChecked());
}
}
Aucun commentaire:
Enregistrer un commentaire