Android自定義控件實現標題欄


方式一:

先建立一個title.xml

代碼如下:

<?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="30dp"
android:background="#00ff00"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="返回"
android:background="#fff"/>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="這是標題欄"
android:gravity="center"
android:layout_weight="1"
android:textSize="24sp"
android:textColor="#fff"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="編輯"
android:background="#fff"/>
</LinearLayout>
</LinearLayout>
標題欄做的丑,不過不影響學。
在activity_main.xml中通過include引入
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/title"/>
</LinearLayout>
在MainActivity中通過調用getSupportActionBar()方法獲取ActionBar的實例,在調用ActionBar的hide()方法將標題欄隱藏起來
public class MainActivity extends AppCompatActivity {

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

ActionBar actionBar=getSupportActionBar();
if (actionBar!=null){
actionBar.hide();
}
}
}
方式二
在title.xml的基礎上。
新建一個活動 TitleLayout,繼承父類Linearlayout
代碼如下:
 public TitleLayout(Context context, AttributeSet attrs) {
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button back=findViewById(R.id.button1);
Button edit=findViewById(R.id.button2);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"你點擊了編輯按鈕",Toast.LENGTH_LONG).show();
}
});
}
}
實現返回和編輯按鈕的監聽事件
 
在activity_main.xml中修改代碼:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--<include layout="@layout/title"/>-->
<com.example.administrator.uilayouttest.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM