2016-03-23 82 views
0

我想打一個應用程序,有報價和作家,我從SQLite的預填充數據庫中獲取的列表如何風格我的TextView和按鈕圖像內的ListView

我想讓這樣的事情 Image

所以在左邊,我有2個textviews(1爲報價,另一個爲作者)

和在右邊,這是一個圖像按鈕,每次我點擊心臟圖像從灰色到紅色,如果再次點擊,則會變成灰色

我已經使用2個textview和另一個xml的1個圖像按鈕來填充我的listview和數據庫。但我不知道如何風格的字體和改變,只要其點擊

這裏的形象是我的代碼

DatabaseOpenHelper.java

public class DatabaseOpenHelper extends SQLiteOpenHelper { 

private static final String DATABASE_NAME = "mqn.db"; 
private static final int DATABASE_VERSION = 1; 

private static final String TABLE_NAME = "quote"; 
public static final String COLUMN_ID = "_id"; 
public static final String COLUMN_QUOTES = "quotesText"; 
public static final String COLUMN_AUTHOR= "author"; 
public static final String COLUMN_FAV = "fav"; 

private SQLiteDatabase database; 

private final Context context; 

// database path 
private static String DATABASE_PATH; 

/** constructor */ 
public DatabaseOpenHelper(Context ctx) { 
    super(ctx, DATABASE_NAME, null, DATABASE_VERSION); 
    this.context = ctx; 
    DATABASE_PATH = context.getFilesDir().getParentFile().getPath() 
      + "/databases/"; 

} 

/** 
* Creates a empty database on the system and rewrites it with your own 
* database. 
* */ 
public void create() throws IOException { 
    boolean check = checkDataBase(); 

    SQLiteDatabase db_Read = null; 

    // Creates empty database default system path 
    db_Read = this.getWritableDatabase(); 
    db_Read.close(); 
    try { 
     if (!check) { 
      copyDataBase(); 
     } 
    } catch (IOException e) { 
     throw new Error("Error copying database"); 
    } 
} 

/** 
* Check if the database already exist to avoid re-copying the file each 
* time you open the application. 
* 
* @return true if it exists, false if it doesn't 
*/ 
private boolean checkDataBase() { 
    SQLiteDatabase checkDB = null; 
    try { 
     String myPath = DATABASE_PATH + DATABASE_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READWRITE); 
    } catch (SQLiteException e) { 
     // database does't exist yet. 
    } 

    if (checkDB != null) { 
     checkDB.close(); 
    } 
    return checkDB != null ? true : false; 
} 

/** 
* Copies your database from your local assets-folder to the just created 
* empty database in the system folder, from where it can be accessed and 
* handled. This is done by transfering bytestream. 
* */ 
private void copyDataBase() throws IOException { 

    // Open your local db as the input stream 
    InputStream myInput = context.getAssets().open(DATABASE_NAME); 

    // Path to the just created empty db 
    String outFileName = DATABASE_PATH + DATABASE_NAME; 

    // Open the empty db as the output stream 
    OutputStream myOutput = new FileOutputStream(outFileName); 

    // transfer bytes from the inputfile to the outputfile 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer)) > 0) { 
     myOutput.write(buffer, 0, length); 
    } 

    // Close the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

} 

/** open the database */ 
public void open() throws SQLException { 
    String myPath = DATABASE_PATH + DATABASE_NAME; 
    database = SQLiteDatabase.openDatabase(myPath, null, 
      SQLiteDatabase.OPEN_READWRITE); 
} 

/** close the database */ 
@Override 
public synchronized void close() { 
    if (database != null) 
     database.close(); 
    super.close(); 
} 

// insert a user into the database 
public long insertUser(String quotesText, String author, String fav) { 
    ContentValues initialValues = new ContentValues(); 
    initialValues.put(COLUMN_QUOTES, quotesText); 
    initialValues.put(COLUMN_AUTHOR, author); 
    initialValues.put(COLUMN_FAV, fav); 
    return database.insert(TABLE_NAME, null, initialValues); 
} 

// updates a user 
public boolean updateUser(long rowId, String quotesText, String author, 
          String fav) { 
    ContentValues args = new ContentValues(); 
    args.put(COLUMN_QUOTES, quotesText); 
    args.put(COLUMN_AUTHOR, author); 
    args.put(COLUMN_FAV, fav); 
    return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0; 
} 

// retrieves a particular user 
public Cursor getUser(long rowId) throws SQLException { 
    Cursor mCursor = database.query(true, TABLE_NAME, new String[] { 
        COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, 
      COLUMN_ID + " = " + rowId, null, null, null, null, null); 
    if (mCursor != null) { 
     mCursor.moveToFirst(); 
    } 

    return mCursor; 
} 

// delete a particular user 
public boolean deleteContact(long rowId) { 
    return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0; 
} 

// retrieves all users 
public Cursor getAllUsers() { 
    return database.query(TABLE_NAME, new String[] { COLUMN_ID, 
        COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null, 
      null, null, null); 
} 

@Override 
public void onCreate(SQLiteDatabase arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // TODO Auto-generated method stub 

} 

} 

QuotesActivity.java

public class QuotesActivity extends AppCompatActivity { 

TextView title; 
Typeface myFont; 
ListView quotesList; 
ListView favLV; 
DatabaseOpenHelper myDbHelper; 
DatabaseAccess databaseAccess; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_quotes); 

    myDbHelper = new DatabaseOpenHelper(this); 

    try { 
     // check if database exists in app path, if not copy it from assets 
     myDbHelper.create(); 
    } catch (IOException ioe) { 
     throw new Error("Unable to create database"); 
    } 

    try { 
     // open the database 
     myDbHelper.open(); 
     myDbHelper.getWritableDatabase(); 
    } catch (SQLException sqle) { 
     throw sqle; 
    } 

    populateListView(); 



    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar); 
    toolbar.setNavigationIcon(R.drawable.back_button); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayShowTitleEnabled(false); 
    title = (TextView) findViewById(R.id.titleQuote); 
    myFont = Typeface.createFromAsset(getAssets(), "Montserrat-Bold.otf"); 
    title.setTypeface(myFont); 
    title.setTextSize(20); 
    title.setTextColor(Color.rgb(240, 239, 223)); 

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
} 

private void populateListView() { 
    Cursor cursor = myDbHelper.getAllUsers(); 
    String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR}; 
    int[] to = new int[] {R.id.quoteLV, R.id.authorLV}; 
    SimpleCursorAdapter myCursorAdapter; 
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0); 
    quotesList = (ListView) findViewById(R.id.quotesList); 
    quotesList.setAdapter(myCursorAdapter); 
} 
} 

Content_quotes.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
app:layout_behavior="@string/appbar_scrolling_view_behavior" 
tools:context="hendrasetiawan.mqn.QuotesActivity" 
tools:showIn="@layout/activity_quotes"> 

<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true"> 

    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

     <ListView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/quotesList" 
      android:layout_gravity="right" 
      android:layout_weight="1" /> 

     <ListView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/favList" 
      android:layout_weight="6" /> 


    </LinearLayout> 



</LinearLayout> 
</LinearLayout> 

quotes_listview.xml

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

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New Text" 
    android:id="@+id/quoteLV" 
    android:textSize="20dp"/> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New Text" 
    android:id="@+id/authorLV" 
    android:textSize="20dp"/> 
</LinearLayout> 

每次我嘗試設置字體的大小/改變行情的活動 的字體我總是在空對象引用的Android得到錯誤

編輯帖子

我logcat的

(注=我quoteLV和authorLV現在文本1和文本) ,我嘗試把text1.setTextSize(50); populateView()

03-23 17:23:30.621 26550-26550 /? I/art:延遲啓用-Xcheck:jni 03-23 17:23:30.659 26550-26550/hendrasetiawan.mqn W/System:ClassLoader引用的未知路徑:/data/app/hendrasetiawan.mqn-1/lib/arm 03-23 17:23:30.953 26550-26590/hendrasetiawan.mqn D/OpenGLRenderer:使用EGL_SWAP_BEHAVIOR_PRESERVED:true 03-23 17:23:30.996 26550-26590/hendrasetiawan.mqn我/ Adreno-EGL :: QUALCOMM構建: 10/21/15,369a2ea,I96aee987eb 03-23 17:23:30.999 26550-26590/hendrasetiawan.mqn I/OpenGLRenderer:初始化的EGL,版本1.4 03-23 17:23:32.201 26550-26550/hendrasetiawan.mqn I/SQLiteAssetHelper:成功打開數據庫mqn.db 03-23 17:23:32.205 26550-26550/hendrasetiawan.mqn I/SQLiteAssetHelper:成功打開數據庫mqn.db 03-23 17:23:32.216 26550-26550/hendrasetiawan .mqn D/AndroidRuntime:關閉關閉VM 03-23 17:23:32.217 26550-26550/hendrasetiawan.mqn E/AndroidRuntime:致命異常:主要 進程:hendrasetiawan.mqn,PID:26550 java.lang。RuntimeException:無法啓動活動ComponentInfo {hendrasetiawan.mqn/hendrasetiawan.mqn.QuotesActivity}:java.lang.NullPointerException:嘗試在空對象引用 處調用虛擬方法'void android.widget.TextView.setTextSize(float)'at android.app.AudioThread.performanceLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app .ActivityThread $ H.handleMessage(ActivityThread.java:1344) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.loop(Looper.java:148) 的機器人。 app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 引起:java.lang.NullPointerException:試圖調用虛函數'void android.widget.TextView.setTextSize(float)'null在android.app.Activity.performCreate(Activity.java:6251)上的對象引用 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android .app.ActivityThread.-wrap11(ActivityThread.java) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344) 在android.os.Handler.dispatchMessage(Handler.java:102) 的機器人。 os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 03-23 17:28: 32.266 26550-26550/hendrasetiawan.mqn I /過程:發送信號。 PID:26550 SIG:9

新的編輯POST

content_quotes.xml

這裏面我只有1的ListView

inside_listview.xml

這裏內幕我有2個textViews和1 ButtonImage

行情活動

該Java,在的setContentView content_quotes.xml 所以,當我風格content_quotes一切。XML,我可以很容易地做到這一點

而現在,我獲取所有從數據庫 引號和作者到2個textviews(這是inside_listview.xml)

,每次我試圖樣式它的2 textviews,我總是得到一個錯誤 是因爲它來自另一個XML?

+1

ü可以發佈您的logcat的想法? – Raghavendra

+0

我已經可以用數據庫填充列表視圖,它的工作原理 但是當我嘗試設置textview(quoteLV.setTextSize(50);)的樣式時,它會引發錯誤。 啊WAIT2 –

+0

可能是字體是不是在你的資產文件夾 –

回答

2

以風格最喜歡的圖像按鈕:

我還沒有看到您的代碼。你說你填充了你的列表視圖,並讓你的項目有兩個文本視圖和一個圖像按鈕。 將圖像按鈕更改爲複選框,以便將心臟按鈕轉換爲紅色和灰色將很容易。

在你的item.xml中有這樣的複選框。

<CheckBox 
    android:layout_margin="8dp" 
    android:layout_gravity="right|top" 
    android:button="@null" 
    android:id="@+id/id_homeListing_fav" 
    android:drawableTop="@drawable/fav" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 

注drawableTop標記其指向fav.xml文件,在fav.xml文件中指定象檢查,未經檢查

音符按鈕標記爲不同的狀態可繪製是空的

代碼fav.xml

<?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/ic_fav_primary" android:state_checked="true"></item> 
    <item android:drawable="@drawable/ic_fav_gray" android:state_checked="false" 
    /> 

在上述收藏。 xml ic_fav_primary是你的紅色圖標,另一個是灰色圖標。

然後將setOnChangeListner設置爲複選框並相應地執行操作。

和自定義文本字體See this Link

+0

感謝您使用CheckBox代碼!至於字體,我已經知道如何使用字體的自定義字體,但問題是,因爲2 textViews(引號和作者)和ListView是不同的XML,我不能風格的兩個textViews,因爲它沒有連接使用ListView活動 –

+0

將上下文傳遞給適配器? – Irfan

+0

對不起,我不知道最新情況,我是這個初學者。 我可以向您發送數據並檢查它嗎?所以它會更清晰。 對不起造成的麻煩 –

1

要更改字體:

  1. 下載你想從互聯網上使用的字體。這似乎是幾乎相同的圖像:http://www.fontspring.com/fonts/typoforge-studio/cervo?utm_source=fontsquirrel.com&utm_medium=matcherator_link&utm_campaign=cervo
  2. 創建src/main/assets/fonts/文件夾
  3. 下載ttfotf字體文件移動到文件夾
  4. 應用下載的字體:
    Typeface type = Typeface.createFromAsset(getAssets(),"fonts/Kokila.ttf"); txtyour.setTypeface(type);

在點擊佈局後更改圖像

yourTextView.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
      yourImageView.setImageDrawable(R.drawable.image); 
    } 
}); 

添加一些填充到兩個的TextView和ImageView的

android:padding="8dp" 

這應該給你如何風格你的佈局

+0

我已經使用它,它的工作原理,但是,quoteLV和authorLV是在另一個XML,我不知道爲什麼,它總是會引發錯誤 –

+0

您可能想要檢查本指南:http://www.vogella.com /tutorials/AndroidListView/article.html#listsactivity_layout –

+0

這可以幫助您在XML中設置樣式並使用適配器。實現和設計佈局更容易。這也將修復空指針異常 –