HorizontalScrollView 横向滑动,点击改变颜色,上一个颜色恢复

横向滑动点击改变颜色
activity_main 布局文件


    
        
            
        
    

代码实现
public class MainActivity extends AppCompatActivity  {


    LinearLayout linrar;
    ArrayList strList;
    TextView textView;
    String str[] = {
      "演员",  "绅士","怎样","","意外","天后","丑八怪","刚刚好","认真的雪","黄色枫叶","其实",
    };

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

    }

    private void initView() {

        linrar = findViewById(R.id.linrar);

        strList = new ArrayList();
        for (int i = 0; i < str.length; i ++){
            strList.add(str[i]);
        }


        for (int i = 0; i < strList.size(); i ++){
            textView = new TextView(this);
            textView.setText(strList.get(i));
            textView.setPadding(20,20,20,20);
            textView.setId(i);
            textView.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
            textView.setTextSize(18);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setLeiXingTab(v.getId());
                }
            });
            linrar.addView(textView);
        }

    }


    private void setLeiXingTab(int pos){
     
        for (int i = 0; i < linrar.getChildCount();i++){

            TextView textView = (TextView) linrar.getChildAt(i);
            if (pos == i){
                textView.setTextColor(getResources().getColor(R.color.colorAccent));
            }else {
                textView.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
            }
        }
    }

}

你可能感兴趣的:(HorizontalScrollView 横向滑动,点击改变颜色,上一个颜色恢复)