标签:09 layout context 自定义 title 布局 16 supportActionBar 加载
一. 添加自定义的布局:
使用 : <include layout = "xxxx">
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*隐藏标题栏*/
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null){
supportActionBar.hide();
}
}
}
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<include layout="@layout/title"/>
</LinearLayout>
二. 自定义布局以及事件的处理
总结:
1.新建类继承自LinearLayout
(LinearLayout为想使用的布局)
2.重写 TitleLayout(Context context, @Nullable AttributeSet attrs)
方法(alt+enter)
3.使用:LayoutInflater.from(context).inflate(R.layout.title, this)
加载该布局
4.其中的事件处理等和 MainActivit y中一致
5.layout中新建布局,xml文件 书写布局
6.如果是标题栏,也要像上述一样隐藏
7.activity_main.xml 中不在使用 include 而是 TitleLayout(包名要全)
/隐藏标题栏/
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null){
supportActionBar.hide();
}
代码示例:
java:
public class TitleLayout extends LinearLayout implements View.OnClickListener {
/**默认必须调用的方法,构造方法————并在其中实现布局的加载*/
public TitleLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
/**布局的加载--默认的方法*/
/**LayoutInflater.from() 方法构建一个LayoutInflater对象 ,然后使用inflate加载布局
* R.layout.title:表示加载的布局
* this:在加载好的布局再加载一个父布局
* */
LayoutInflater.from(context).inflate(R.layout.title, this);
/**在这里面就可以进行自定义布局事件的处理了*/
// 布局控件的引用
Button titleBack = findViewById(R.id.title_back);
TextView titleEdit = findViewById(R.id.title_edit);
// 事件的绑定
titleEdit.setOnClickListener(this);
titleBack.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.title_back:{
((Activity) getContext()).finish();
break;
}
case R.id.title_edit:{
/**注意这里要使用getContext()*/
Toast.makeText(getContext(), "you clicked edit buton", Toast.LENGTH_SHORT).show();
break;
}
default:
break;
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<com.example.uicustomviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
记录于: 2021年9月16日21:26:58
标签:09,layout,context,自定义,title,布局,16,supportActionBar,加载 来源: https://blog.csdn.net/JUSTLOVEBOY/article/details/120337334
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。