如何使用按钮逐步遍历2D数组?

时间:2018-07-21 09:30:01

标签: android arrays for-loop iteration

在android中按下按钮后,我必须一步一步地遍历2D循环

<!--Curved stack--> <Frame CornerRadius="5" HorizontalOptions="Center" VerticalOptions="Start" HasShadow="True" Padding="0"> <StackLayout Padding="10,5,10,5" Orientation="Horizontal" BackgroundColor="White" > <Image Source="settingsIcon" HeightRequest="25" WidthRequest="25" Aspect="Fill" /> <Label Text="Filter" FontSize="Medium" VerticalTextAlignment="Center" VerticalOptions="Center"/> </StackLayout> </Frame>

输出应为:

3 4 3 4 5 4 2 3 4

如何在循环中使用clicklistener?

1 个答案:

答案 0 :(得分:0)

尝试这样:

public class Main extends AppCompatActivity {
int[][] array = new int[][]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

int rows = 0;
int columns = 0;
TextView textView;


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView = (TextView) findViewById(R.id.text);


    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (columns < array[rows].length) {
                textView.setText("After Button pressed: " + array[rows][columns]);
                columns++;
            } else {
                rows++;
                if (rows != array.length) {
                    columns = 0;
                    textView.setText("After Button pressed: " + array[rows][columns]);
                    columns++;
                } else {
                    rows = 0;
                    columns = 0;
                }
            }
        }
    });
}