TextView通过按钮加载数组内容

2017-07-21  本文已影响0人  闲人逛小白

1.新建一个项目,在主布局中添加一个TextView和一个Button按钮。


main.xml
<pre>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:layout_width="match_parent"
    android:text="Small Text"
    android:gravity="center"
    android:textColor="#BC2F26"
    android:id="@+id/tv1"/>

<Button
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:text="下一个"
    android:id="@+id/bt1"
    android:onClick="下一个"/>

</LinearLayout>
</pre>


android:onClick属性是设置可点击,在主布局中设置之后在Java代码中为其设置监听器监听事件方便些。


2.Java代码:
<pre>
package com.mycompany.myapp10;

import android.app.;
import android.os.
;
import android.view.;
import android.widget.
;

public class MainActivity extends Activity
{

//声明控件
private TextView tv1;
private Button bt1;
//定义一个字符串数组
private String[] str={"第一","第二","第三","第四","第五"};
//定义一个int类型全局变量
private int i;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //绑定控件ID
    tv1=(TextView) findViewById(R.id.tv1);
    bt1=(Button) findViewById(R.id.bt1);
    }
    </pre>
//控件点击事件
public void 下一个(View view){
   //使用if判断
  //i++必须设置在tv1控件后面,设置前面会超过数组角标范围,导致程序停止运行
    if(i<str.length){
        tv1.setText(str[i]);
        i++;

<pre>
在i++下面加入此if判断
//可实现数组内容循环显示
if(i==str.length){
i=0;
}

}}}


3.解释:
通过if进行判断符合就执行,
若i的值小于数组长度,
tv1就setText()获取数组中角标0的数据"第一"

数组的数据通过角标(索引)一一获取,
它从0开始算起,刚好i的初始值为0,
所以第一次点击按钮tv1获取了数据"第一",
后再执行i++


顺便说下数组长度它则是从1算起的


而第二次点击按钮,i的值变成了1,
此时tv1获取了数据"第二",
它对应的数组角标是1,再执行i++

以此类推,直到i的值不再小于等于数组长度后停止加载数组内容。

我们设置的数组有五个字符串,它的长度就是5
,而它的5个字符串对应的角标就是从0算起,
所以i的值是if判断中i++就到4就停止了,
这也是前面提到的超过角标范围程序出错原因。


你想想,若是i的值加到5,
那它对应的数组长度应该是
第六个字符串吧,但是我们
数组中却没定义第六个吧!


4.小白一枚,记录学习过程。
文章中有不足,均可指点指点,
亦有什么更好的实现(相似)方法望不奢指教,
共勉齐学习!


TextView通过按钮加载数组内容
上一篇下一篇

猜你喜欢

热点阅读