MCQView in Android
public class MCQView extends View {
private String questionText;
private List answerChoices;
private int selectedAnswer;
private Paint questionPaint;
private Paint answerPaint;
private Rect questionRect;
private List answerRects;
public MCQView(Context context) {
super(context);
init();
}
public MCQView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MCQView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// Initialize instance variables and paint objects
questionText = "";
answerChoices = new ArrayList<>();
selectedAnswer = -1;
questionPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
questionPaint.setColor(Color.BLACK);
questionPaint.setTextSize(40);
answerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
answerPaint.setColor(Color.BLACK);
answerPaint.setTextSize(30);
questionRect = new Rect();
answerRects = new ArrayList<>();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Calculate the desired size for your MCQ view
int desiredWidth = 500;
int desiredHeight = 300;
setMeasuredDimension(desiredWidth, desiredHeight);
}
@Override
protected void onDraw(Canvas canvas) {
// Draw the question text and answer choices on the canvas
questionRect.set(0, 0, getWidth(), getHeight() / 2);
canvas.drawText(questionText, questionRect.left + 20, questionRect.top + 50, questionPaint);
answerRects.clear();
int answerTop = getHeight() / 2 + 50;
for (int i = 0; i < answerChoices.size(); i++) {
String answerText = answerChoices.get(i);
Rect answerRect = new Rect();
answerRect.set(0, answerTop, getWidth(), answerTop + 80);
answerRects.add(answerRect);
canvas.drawText(answerText, answerRect.left + 20, answerRect.top + 50, answerPaint);
if (i == selectedAnswer) {
Paint selectedPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
selectedPaint.setColor(Color.BLUE);
canvas.drawRect(answerRect, selectedPaint);
}
answerTop += 100;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Handle touch events to allow the user to select an answer choice
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
float x = event.getX();
float y = event.getY();
for (int i = 0; i < answerRects.size(); i++) {
if (answerRects.get(i).contains((int) x, (int) y)) {
selectedAnswer = i;
invalidate();
return true;
}
}
break;
}
return super.onTouchEvent(event);
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
invalidate();
}
public void setAnswerChoices(List answerChoices) {
this.answerChoices = answerChoices;
invalidate();
}
public void setSelectedAnswer(int selectedAnswer) {
this.selectedAnswer = selectedAnswer;
invalidate();
}
public String getQuestionText() {
return questionText;
}
public List getAnswerChoices() {
return answerChoices;
}