Overview
今天学习Android的UI显示,导航栏的操作。
开发环境
- Android Studio 3.6
- JAVA
- Android 11 开发者预览版
代码讲解
按照我们的国际惯例,我们来看一下这个demo的主要布局文件。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/mainTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_dark"
tools:ignore="MissingConstraints" />
<androidx.viewpager.widget.ViewPager
android:id="@+id/mainViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
这个就是我们的主要活动的布局文件了。这个布局很简单,没什么好讲的。就是添加了一个TabLayout和一个ViewPager控件,所实现的。
然后我们在看一下我们的活动页代码:
public class MainActivity extends AppCompatActivity {
private List<View> pagers = new ArrayList<>();
@SuppressLint("ResourceType")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
TabLayout tabLayout = this.findViewById(R.id.mainTabLayout);
ViewPager viewPager = this.findViewById(R.id.mainViewPager);
//set TabLayout display mode
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
//set TabLayout Colors
tabLayout.setTabTextColors(ContextCompat.getColor(this, android.R.color.white), ContextCompat.getColor(this, android.R.color.white));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, android.R.color.white));
ViewCompat.setElevation(tabLayout, 10);
//Bind TabLayout and ViewPager
tabLayout.setupWithViewPager(viewPager);
//Use ASCII
int a = 91;
for (int i = 65; i < a; i++) {
//Convert ASCII
String name = String.valueOf((char) Integer.parseInt(String.valueOf(i)));
//Add item to TabLayout
tabLayout.addTab(tabLayout.newTab().setText(name));
//Crate a new View
View view = View.inflate(MainActivity.this, R.layout.layout, null);
((TextView) view.findViewById(R.id.pageID)).setText(name);
//add the new view to the collection
pagers.add(view);
}
//Binding data
viewPager.setAdapter(new viewPagerAdapter(pagers));
//The TabLayout title disappears after the ViewPager is bound,and you need to rebind the value of the tab.
for (int i = 0; i < 26; i++) {
String name = String.valueOf((char) Integer.parseInt(String.valueOf(i + 65)));
Objects.requireNonNull(tabLayout.getTabAt(i)).setText(name);
}
}
}
正如我们代码中的注释所示。显示初始化我们的控件,然后我们将我们的TabLayout控件设置一下细节。
这里需要设置的有。TabMode
TabTextColors
SelectedTabIndicatorColor
,然后将我们的ViewPager和我们的TabLayout进行绑定。
这样我们的基础操作就完成了。
然后我们的将我们的数据源绑定到我们的控件中去,还是非常的简单。往TabLayout中添加Tab项目。这里我们使用到的方法是TabLayout.addTab()
方法进行添加。
这样的和话我们的操作就完成。但是这里使用到的ViewPager绑定数据在这里就不作详细的操作了。我之前的博客也都有。