2011-01-26 29 views

回答

15

是的,你可以。

public class MyActivity extends Activity { 
    protected void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 

     final Button button = new Button(this); 
     button.setText("Press me!"); 
     setContentView(button); 

     button.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       // Perform action on click 
      } 
     }); 
    } 
} 
7

我可以創建一個使用Java語言相同的GUI?

是的,你可以創建Java代碼也GUI由@dtmilano回答,但總的來說它不是Android應用一個很好的做法。在一個小應用程序的情況下它很容易,但如果您要爲最終用戶開發應用程序,則必須使用XML文件創建GUI。當您想要開發具有不同顯示尺寸和不同不同語言的多種設備的應用程序時,它也很有用。

最佳做法是儘量避免使用Java創建GUI,而應儘量使用XML

+0

爲什麼用Java創建UI是一種不好的做法?如果我想在不使用GL的情況下更改TextView,圖像或其他UI對象的位置,該怎麼辦? – iOSAaronDavid 2015-09-14 20:57:45

+0

不是一個有用的「答案」 – eric 2016-01-07 16:58:12

-1

如果您使用的是Eclipse,你可以到文件夾資源從項目/佈局,其中,你會發現main.xml文件 右鍵單擊該文件,並選擇打開方式/ Android的佈局編輯器 在那裏,你會看到一個圖形需要的工具,將生成所有被列入main.xml中的文件

+0

雅沒有回答這個問題。 – eric 2016-01-07 16:53:44

0

我發現這篇文章有用,也許這是對你有好處太 Creating an Android User Inteface in java Code

首先你需要創建一個對象的佈局像這樣

RelativeLayout myLayout = new RelativeLayout(this); 

然後創建例如按鈕這樣

Button myButton = new Button(this); 

則按鈕視圖需要添加作爲子到RelativeLayout的視圖,這反過來,經由呼叫顯示給的setContentView()方法活動實例

myLayout.addView(myButton); 
setContentView(myLayout); 

一旦推出的,可見的結果將是一個包含出現在RelativeLayout的視圖的左上角沒有文本的按鈕。

0

絕對可以使用java設計你的Android UI。 下面是創建按鈕的一個小例子。

按照以下步驟

  1. 進口的佈局包(在這裏,我進口android.widget。的RelativeLayout)
  2. 進口鈕釦式封裝
  3. 創建一個佈局對象
  4. 創建一個按鈕對象
  5. 添加按鈕佈局
  6. 設置內容的瀏覽

下面是代碼

package com.example.vmbck.app3; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.RelativeLayout; 
import android.widget.Button; 


public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //create layout 
    RelativeLayout myLayout = new RelativeLayout(this); 
    //set background color of the layout to Green 
    myLayout.setBackgroundColor(Color.GREEN); 

    //create button 
    Button myButton = new Button(this); 
    //set button's background color to red 
    myButton.setBackgroundColor(Color.RED); 
    //set button's text to Click Me 
    myButton.setText("Click Me"); 

    //add button to layout 
    myLayout.addView(myButton); 
    //View the content 
    setContentView(myLayout); 
    } 

} 
相關問題