简体   繁体   English

编辑文本背景资源

[英]Edit Text Background Resource

In my activity is one EditText, one Toggle Button and one Test Button. 在我的活动中是一个EditText,一个Toggle Button和一个Test Button。 If my ToggleButton Pressed Edit Text Backgroud set in Red Style (red.xml), and when not pressed set in Green Stlye (green.xml). 如果我的ToggleButton已按下,则将Edit Text Backgroud设置为红色样式(red.xml),如果未按下,则将其设置为Green Stlye(green.xml)。 But when I press Test Button alredy Write me Red :'( 但是当我按下测试按钮时,把我写成红色:'(

Please Help me!! 请帮我!!

My Code is here: 我的代码在这里:

public class MainActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

ToggleButton Toggle;
EditText ettext;
Button test;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toggle=(ToggleButton)findViewById(R.id.tbkapcsolo);
    Toggle.setOnCheckedChangeListener(this);

    ettext=(EditText)findViewById(R.id.etszovegmezo);

    test=(Button)findViewById(R.id.btnMent);
    test.setOnClickListener(this);

}



@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked){
        ettext.setBackgroundResource(R.drawable.red);

    }else ettext.setBackgroundResource(R.drawable.green);
}

@Override
public void onClick(View v) {

    Drawable style=ettext.getBackground();
    Drawable green=getResources().getDrawable(R.drawable.green);


    if(style==green){
        Toast.makeText(this,"GREEN",Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this,"RED",Toast.LENGTH_LONG).show();

    }
}

} Thank you for help!! } 谢谢你的帮助!!

You have assigned onClickListner to Button as well. 您还已将onClickListner分配给Button。 What ever code you have in onClickListner wil be executed. 您在onClickListner中拥有的所有代码都将被执行。 Remove onClickListner from button or write some code for button. 从按钮中删除onClickListner或为按钮编写一些代码。

Hope this will help you 希望这个能对您有所帮助

The problem could be with the Toggle and the onCheckedChanged() method. 问题可能出在Toggle和onCheckedChanged()方法上。 Try setting your Toggle to true or false before you set the onCheckdChangedListener. 在设置onCheckdChangedListener之前,请尝试将Toggle设置为true或false。

You can do this in the xml if you do android:checked="true" like this: 如果您像这样执行android:checked =“ true”,则可以在xml中执行此操作:

<Switch 
   android:id="@+id/switchid"
   android:checked="true"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM