2014-09-24 30 views
0

的一部分,因爲在主題我的應用跳過代碼。不要問我爲什麼要使用線程,它也發生在try/catch上。經過幾個小時的測試,我發現它與.xml中的android.support.v4.widget.DrawerLayout有關。有誰知道這個解決方案?我的android應用跳過代碼

public class MainActivity extends Activity { 

private String[] drawerListViewItems = new String[]{"Test","Also test","Guess what","Another test"}; 
private ListView drawerListView; 
String a="one"; 
int i=0; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // get list items from strings.xml 
    // drawerListViewItems = getResources().getStringArray(R.array.items); 
    TextView lol = (TextView) findViewById (R.id.textView1); 
    lol.setText("#YOLO"); 
    new Thread (new Runnable() { // This whole thread is skipped for no reason. 
     public void run() { 
       a="SWAG"; 
       i++; 
      }    
    }).start(); 
    lol.setText(a+" "+i); 
    // get ListView defined in activity_main.xml 
    drawerListView = (ListView) findViewById(R.id.left_drawer); 

      // Set the adapter for the list view 
    drawerListView.setAdapter(new ArrayAdapter<String>(this, 
      R.layout.drawer_listview_item, drawerListViewItems)); 

} 

}

當然輸出爲 「一個0」 在我的應用程序。我希望它是「SWAG 1」,我需要它在線程中。另外,不要問我爲什麼用串那樣:)呵呵,有.xml文件:

<android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/drawer_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<!-- The main content view --> 
<RelativeLayout 
    android:id="@+id/content_frame" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView android:text="TextView" 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 

<!-- The navigation drawer --> 
<ListView android:id="@+id/left_drawer" 
    android:layout_width="240dp" 
    android:layout_height="match_parent" 
    android:layout_gravity="start" 
    android:choiceMode="singleChoice" 
    android:divider="#666" 
    android:dividerHeight="1dp" 
    android:background="#333" 
    android:paddingLeft="15sp" 
    android:paddingRight="15sp" 
    /> 

回答

1

它不會被跳過。你正在做錯誤的假設,UI線程正在等待你的線程完成它的執行。快速修復的方法是更新TextView

private void updateTextView() { 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      TextView lol = (TextView) findViewById (R.id.textView1); 
      lol.setText(a+" "+i); 
     } 
    }); 
} 

並在更新數據後在您的線程中調用此方法。還要注意的是setText必須在UI線程

+1

謝謝,它完美的作品。 – Darknez 2014-09-24 15:39:32

0

線程不跳過運行。你假設你的整個程序同步運行,而不是。您編寫它的方式,UI線程無法正確地與您創建的線程進行通信。

當你的代碼打new Thread(...)的一部分,它會產生一個新的線程,同時運行到UI線程。所以a的值可能會或可能不是您所期望的,具體取決於您的背地線是否在setText()之前或之後完成。

有多種與UI線程交流的方式。

使用Handler並從後臺線程發送消息給UI線程。

使用AsyncTask並設置在onPostExecute

使用runOnUIThread更新值作爲其他答案建議。

或者在你的情況下不產生另一個線程。

Here一些關於多線程在Android的更多信息。

+0

另外,謝謝你的回答。我會仔細看看的。 – Darknez 2014-09-24 15:40:33