[英]How to change the text color of a Text View using onclick(), using button?
What I want to do is change the text color of a text view on a button press using onClick(). 我想做的是使用onClick()更改按钮按下时文本视图的文本颜色。 In my layout file, there's one text view and 2 buttons with android:onClick="onClick" attribute.
在我的布局文件中,有一个带有android:onClick =“ onClick”属性的文本视图和2个按钮。
This is my code: 这是我的代码:
package ic.lunar.tictactoefree;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
public class SettingsActivity extends Activity {
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
public void onClick(Button b){
tv1 = (TextView)findViewById(R.id.hello);
if(b.getId()==R.id.grey){
tv1.setTextColor(Color.RED);
}
if(b.getId()==R.id.white){
tv1.setTextColor(Color.BLUE);
}
}
}
now whenever I click any of the 2 buttons, the app force closes. 现在,每当我单击两个按钮中的任何一个时,应用程序强制关闭。 What to do to make it work.
如何使其正常工作。 I want to get the color changed according to the button pressed.
我想根据按下的按钮更改颜色。
Change to 改成
public void onClick(View v){ // method signature
Assuming you have buttons in settings.xml 假设您在settings.xml中有按钮
android:onClick="onClick" // for buttons in xml
Initialize in onCreate 在onCreate中初始化
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
tv1 = (TextView)findViewById(R.id.hello);
}
And 和
public void onClick(View v){
switch(v.getId())
{
case R.id.grey:
tv1.setTextColor(Color.RED);
break;
case R.id.white:
tv1.setTextColor(Color.BLUE);
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.