【问题标题】:how to get same Background drawable with different button android如何使用不同的按钮android获得相同的背景可绘制
【发布时间】:2014-09-26 07:30:12
【问题描述】:

您好,我遇到了来自相同可绘制 xml 的相等 id 背景的问题。

我有像这样的 2 个切换按钮的视图

<ToggleButton
    android:id="@+id/gambar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/g1"
    android:text=""
    android:textOn=""
    android:textOff="" />

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/g1"
    android:text=""
    android:textOn=""
    android:textOff="" />

使用相同的 android:background,我如何才能为我的代码获取相同的 id 源?

我有这样的主要活动

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gamescene);

    this.tg = (ToggleButton) findViewById(R.id.gambar1);
    this.tg1 = (ToggleButton) findViewById(R.id.toggleButton1);

    tg.setOnClickListener(this);
    tg1.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    if(v == tg){
        Toast.makeText(this, "On " + v.getBackground().getConstantState(), Toast.LENGTH_SHORT).show();
    } else if(v == tg1){
        Toast.makeText(this, "On " + v.getBackground().getConstantState(), Toast.LENGTH_SHORT).show();

    }

}

和这样的可绘制xml

<selector xmlns:android="http://schemas.android.com/apk/res/android" >


<item android:state_checked="true" 
    android:state_enabled="true"
    android:drawable="@drawable/bell"/>

<item android:state_checked="false" 
    android:state_enabled="true"
    android:drawable="@drawable/hint"/>

<item android:state_checked="false" 
    android:state_enabled="false"
    android:drawable="@drawable/blank"/>

但是,我得到了来自相同背景的不同状态列表。如何在我的 Activity 中捕获相同的资源名称条目“g1”?

对不起我的英语不好

谢谢

【问题讨论】:

    标签: android xml background drawable android-togglebutton


    【解决方案1】:

    你可以用这个得到它

    getResources().getDrawable(R.drawable.g1);

    【讨论】:

    • 啊谢谢我得到了我想要的想法,tg.getResources()tg1.getResource 生成相同的结果。再次感谢
    • upss 抱歉我的代码有问题,为什么使用不同的可绘制资源我得到相同的资源哈希?如何通过主活动上的切换按钮获取资源条目名称?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2012-02-17
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    相关资源
    最近更新 更多