簡體   English   中英

在Android中用一行將一個TextView中的文本分開

[英]Separating text in one TextView by a line in Android

我有一個TextView ,它將顯示數據庫中的所有內容。 由於我不知道如何根據數據庫生成TextView的數量,因此我想知道是否有任何方法可以在一個String項之后設置可見行。 例,

List of items
book1 love yourself
total of 3
book2 love you
total of 2

如您所見,如果我將所有內容都顯示在一個TextView ,則很難確定單獨的書,因此我想知道是否有什么我可以做來分開的。

如果您將來自數據庫的書籍名稱放在這樣的ArrayList中

public ArrayList<String> getAllBooks(){
    ArrayList<String> alArrayList  = new ArrayList<String>();
    Database db = getWritableDatabase();
    Cursor cursor = db.query("BOOKS", null, null, null, null, null, null );
    if (cursor!=null && cursor.moveToFirst()) {
        do{

        String book = cursor.getString(cursor.getColumnIndex("book_name"));
        alArrayList.add(book);

        }while(cursor.moveToNext());
        db.close();
    }

    return alArrayList;
}

然后,您可以使用此ArrayList創建所需的輸出

    public void setBooks(){
        ArrayList<String> bookNames = new YourDatabseName(this, version).getAllBooks(); 

        LinearLayout layout = (LinearLayout) findViewById(R.id.bookslayout);      
        LayoutParams textViewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

        TextView heading = new TextView(this);
        heading.setText("List of items");
        heading.setLayoutParams(textViewLayoutParams);
        layout.addView(textView);

        if(bookNames.size()>0){
            for(int i = 0; i<=bookNames.size();i++){

                TextView book= new TextView(this);
                book.setText("Book "+ (i+1) +" "+bookNames.get(i).toString());
                book.setLayoutParams(textViewLayoutParams);
                layout.addView(textView);

            }
        }

        TextView footer= new TextView(this);
        footer.setText("Total of "+bookNames.size());
        footer.setLayoutParams(textViewLayoutParams);
        layout.addView(textView);
    }

現在,您需要像這樣的活動布局中的LinearLayout

<LinearLayout
android:id="@+id/bookslayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM