2012-07-07 20 views
1

TestaActivity.java指定值到一個TextView從不同類

public class TestaActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     tvText=(TextView)findViewById(R.id.textView1); 
     tvText.setText("Sample"); 
    } 
} 

Print.java

public class Print { 
    public Print(Context tempContext) { 
     //I want to assign the value to the tvText from here 
    } 
} 

在上面的例子中,你可以看到我在tvText設置文本「樣品」。以同樣的方式,我需要在創建後在Print類中爲textView1 ID分配一些值。

請幫我找出辦法。

回答

1

嘗試爲:

public class Print { 
protected TestaActivity context; 
    public Print(Context tempContext) { 

     context = tempContext; 
    } 
    public void changetextViewtext(final String msg){ 
      context.runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
       //assign the value to the tvText from here 
        context.tvText.setText("Hello Test");  
       } 
      }); 
     } 
} 

Print

public class TestaActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     tvText=(TextView)findViewById(R.id.textView1); 
     tvText.setText("Sample"); 
     Print myPrint = new Print(this); 
      myPrint.changetextViewtext("Hello World !!!"); 
    } 
} 

如您需要調用從活動changetextViewtext的量變到質變的TextView文本!!!! :)

2

如果你的類打印當TestaActivity在屏幕上時被實例化,那麼你可以獲得tvText引用,以某種方式傳遞給Prints以引用TestaActivity。 也許你可以通過構造函數傳遞:

從TestaActivity你這樣做:

Print print = new Print(this); 

其中這代表TestaActivity的實例。 ,然後在打印的代碼,你可以這樣做:

TextView tvText = (TextView)((TestaActivity)context.findViewById(R.id.textView1)); 
tvText.setText("Sample"); 

另一種解決方案是提供從TestaActivity接口,透明的之外,其管理上的TextView(或其他)所做的更改。 類似的東西:

private TextView tvText; 

public void setTvText(String str){ 
     tvText.setText(str); 
} 

,然後在打印類:

((TestaActivity)context).setTvText("Sample"); 
1

@imran - 該解決方案是正確的,只是你想要通過TextView的作爲構造函數或參數方法。

將方法中的TextView編碼不好,因爲您無法重用它。