activity_main 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="@+id/linrar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
</HorizontalScrollView>
</LinearLayout>
</LinearLayout>
代码实现
public class MainActivity extends AppCompatActivity {
LinearLayout linrar;
ArrayList<String> 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<String>();
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));
}
}
}
}