有for循环的建议

时间:2011-11-10 21:48:48

标签: android android-layout

所以我一直在为Android制作数学程序,我遇到了一个问题,我需要使用for循环打印一系列数字,我不确定如何让我的程序以我喜欢的方式打印变量,我已经尝试过TextView,但它只显示第一个变量,我是否需要使用ListView?以及如何设置文本?这是我迄今为止尝试过的xml和代码文件:

类:

public class Screen extends ListActivity {

public EditText txtbound1;
private double a = 0;
private double b1 = 0;
private double c = 0;

//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();

//DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
ArrayAdapter<String> adapter;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screen1);
    Bundle b = getIntent().getExtras(); 
    double bound = b.getDouble("name");

    adapter=new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            listItems);
        setListAdapter(adapter);



    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    //public void addItems(View v) {
    // listItems.add("Clicked : "+clickCounter++);
    // adapter.notifyDataSetChanged();



    for(double i = bound;i>0;i--)
    {
                    a = bound;
                    b1 = a * 2;
                    c = a*3;
                    bound--;

}
}
    public void addItems(double a, double b1, double c) { // or you can parse it before and have string parameters
         listItems.add(Double.toString(a) + " " + Double.toString(b1) + " " + Double.toString(c));
         adapter.notifyDataSetChanged();

         }
     }

和布局是:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/addBtn"
android:text="Add New Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="addItems"/>

<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
</LinearLayout>

所以我们假设用户输入5作为绑定,我希望这样显示:

  • A B C
  • 5 10 15
  • 4 8 12
  • 3 6 9
  • 2 4 6
  • 1 2 3

然而它只显示5 10和15行,如何编辑for循环以使其有效?我需要将a,b1和c设置为数组吗?或ListView工作?我之前从未使用过ListView,所以如果ListView是我需要的,请告诉我如何在xml布局中初始化它以及如何将变量打印到它之前,我已经完成了,谢谢

2 个答案:

答案 0 :(得分:1)

  1. 你的循环逻辑有缺陷。设置a = bound意味着每次进入循环a将为5,因为永远不会修改bound。看起来您想设置a = i(或者只是使用i进行计算)。

  2. TextView.setText()用新文本替换视图的当前文本,覆盖以前显示的任何内容。您可以改为使用TextView.append()或预先构建整个字符串(例如使用StringBuilder等),然后在循环结束后调用TextView.setText()一次。

答案 1 :(得分:0)

是的,如果您使用Listview更有意义。结帐this post

在建议的“addItems”方法中,简单的连接就足够了:

public void addItems(double a, double b1, double c) { // or you can parse it before and have string parameters
 listItems.add(Double.toString(a) + " " + Double.toString(b1) + " " + Double.toString(c));
 adapter.notifyDataSetChanged();
}
相关问题