2010-12-01 189 views
0

因此,我对Android的整个开发事情都很陌生,而且我不知道java的光滑程度。我试着教自己,所以我认为这将是一个很好的资源。我读过devoloper.android资源,但我仍然不明白,所以这是我的问题。 我正在制作一个简单的应用程序,它会在按下按钮时更改背景颜色。我如何让按钮做到这一点?按钮控制?

任何外部资源/例子将不胜感激

这里是到目前为止我的代码:

IntroActivity.java

package com.flashcalc; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View.OnTouchListener; 
import android.widget.Button; 

public class IntroActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    } 
} 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@color/all_white"> 
<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" 
    android:textColor="@color/all_black" 
    android:gravity="center_horizontal"/> 
<Button android:text="@string/ChangeColor" 
android:id="@+id/ChangeColor" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:gravity="center_horizontal|center_horizontal|center" 
android:layout_gravity="center_horizontal|center_horizontal|center"> 
</Button> 
</LinearLayout> 

字符串。 xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string name="hello">Tjs Flashlight</string> 
    <string name="app_name">FlashCalc</string> 
    <string name="ChangeColor">I Love Buttons</string> 
    <color name="all_white">#FFFFFF</color> 
    <color name="all_black">#000000</color> 
</resources> 

回答

0

您需要获取您的linearlayout的视图并将其设置为背景颜色。

首先,您需要在xml中为您的LinearLayout分配一个ID。然后在你的按钮的onclicklistener,做到这一点。

LinearLayout ll = (Linearlayout) findViewById(R.id.layoutid); 
ll.setBackgroundColor(); //I think this is what it's called 

我忘记了setBackgroundColor函数的功能,你得看看。

在尝试像这样做自己的东西之前,你应该真的经历所有hello android教程。在寻求帮助之前,你甚至还没有尝试过任何东西。

0

你需要做几件事情。首先,您需要为任何要更改颜色的LinearLayout,TextView或其他任何内容添加一个id。然后,您需要将代码附加到按钮才能在点击时运行。有两种方法可以做到这一点。首先,你可以一个onClick处理程序到你的XML:

android:onClick="buttonChangeColor" 

,然后在类中,添加适当的方法:

public void buttonChangeColor(View v) { 
    LinearLayout ll = (LinearLayout) findViewById(R.id.whateverYouCalledThis); 
    ll.setBackgroundColor(0xffffff); //white 
} 

您还可以将一个方法使用setOnClickListener: http://developer.android.com/reference/android/view/View.html#setOnClickListener(android.view.View.OnClickListener

另一件可能有用的事情是将您的颜色值存储在资源文件(res/values/colors.xml)中:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="color_0">#ffffff</color> 
</resources> 

然后,您可以在代码中使用该颜色:

ll.setBackgroundColor(getResources().getColor(R.color.color_0));