【问题标题】:Android reset color of dynamic created buttons programmaticallyAndroid以编程方式重置动态创建按钮的颜色
【发布时间】:2015-01-19 15:54:52
【问题描述】:

我在 linearlayout 水平滚动视图中动态创建按钮,单击时我得到选定的按钮位置。我改变了点击按钮的文字颜色。但我的问题是我怎样才能休息其他按钮的文字颜色。

例如,我在线性布局水平滚动视图中有 6 或 7 个按钮,当我单击位置 1 按钮时,它的文本颜色发生了变化,但是当我单击位置 2 按钮时,我想重置位置 1 或所有按钮的文本颜色。我该怎么做?

这是我的代码。

String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"};
private LinearLayout ll;
Button btn;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);

    for(int i = 0; i < categories.length; i++) {
        btn = new Button(this);
        btn.setText(categories[i]);
        btn.setBackgroundColor(Color.parseColor("#ffffff"));
        btn.setOnClickListener(buttonClick);
        ll.addView(btn);
        int idx = ll.indexOfChild(btn);
        btn.setTag(Integer.toString(idx));
    }
}

OnClickListener buttonClick = new OnClickListener() {
    public void onClick(View v) {
        String idxStr = Integer.toString(ll.indexOfChild(v));

        if(v instanceof Button){
            ((Button)v).setTextColor(Color.parseColor("#00aeef"));
         }

        Toast.makeText(MainActivity.this, idxStr, 6000).show();
    }
};

【问题讨论】:

    标签: android android-linearlayout android-button horizontalscrollview


    【解决方案1】:

    也许通过主布局子元素进行一些迭代?

    for(int i=0; i<ll.getChildCount(); i++){
        if(ll.getChildAt(i) instanceOf Button)
            ((Button)ll.getChildAt(i)).
                setTextColor(Color.parseColor("#00aeef"));
    }
    

    您的活动中也不需要Button btn;,此引用未使用(并且仅保留最后添加的按钮)

    【讨论】:

    • @user3555472 如何再次从未选中的按钮中删除颜色?我只想为那些瞬间选择的按钮文本颜色保持变化。
    猜你喜欢
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多