What I want is to change the accessibility order, the order in which the screen reader, the TalkBack in that Android case, read the elements, after pressing a button. This is what I tried by far, but it doesn't work, the order is still the initial descending ones. (In my example buttons are in order b1, b2, b3, and after I presso button changeorder I want the order to become b3,b1,b2).
CODE:
Button b1,b2,b3, changeorder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearlayout = findViewById(R.id.linearlayout);
changeorder = new Button(this);
changeorder.setText("Presso to change order");
changeorder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("BUTTON","Clicked change order button");
changeorder.setAccessibilityTraversalBefore(b3.getId());
b3.setAccessibilityTraversalAfter(changeorder.getId());
b3.setAccessibilityTraversalBefore(b1.getId());
b1.setAccessibilityTraversalAfter(b3.getId());
b1.setAccessibilityTraversalBefore(b2.getId());
b2.setAccessibilityTraversalAfter(b1.getId());
changeorder.setText("Order changed b3,b1,b2");
}
});
changeorder.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
linearlayout.addView(changeorder);
b1 = new Button(this);
b1.setText("BUTTON 1");
b1.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
linearlayout.addView(b1);
b2 = new Button(this);
b2.setText("BUTTON 2");
b2.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
linearlayout.addView(b2);
b3 = new Button(this);
b3.setText("BUTTON 3");
b3.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
linearlayout.addView(b3);
}
Your Button
s don't have IDs, so when you call getId()
in b3.setAccessibilityTraversalBefore(b1.getId());
, etc., you're getting View.NO_ID
, so the traversal order isn't being set up correctly.
To fix it, define some IDs in XML:
<resources>
<item type="id" name="changeOrderButton" />
<item type="id" name="button1" />
<item type="id" name="button2" />
<item type="id" name="button3" />
</resources>
and then set them on your buttons with View.setId
when you create them:
b1 = new Button(this);
b1.setId(R.id.button1); // Add the ID so that accessibility traversal can identify this view
b1.setText("BUTTON 1");
b1.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
linearlayout.addView(b1);
(and do the same for the rest of the buttons)