<?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" android:orientation="horizontal"> <ImageView android:layout_marginTop="10dp" android:id="@+id/title_img1" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:src="@drawable/default_sdk_login"/> <ImageView android:layout_marginTop="10dp" android:id="@+id/title_img2" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:src="@drawable/detail_loading"/> <ImageView android:layout_marginTop="10dp" android:id="@+id/title_img3" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:src="@drawable/detail_search_icon"/> </LinearLayout>public class TitleView extends LinearLayout{ ImageView img1; ImageView img2; ImageView img3; public TitleView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public void setLeftListener(OnClickListener listener){ img1.setOnClickListener(listener); } public void setRightListener(OnClickListener listener){ img3.setOnClickListener(listener); } public TitleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); } public TitleView(Context context) { super(context); } private void initView(Context context){ LayoutInflater.from(context).inflate(R.layout.title_main,this); img1 = (ImageView) findViewById(R.id.title_img1); img2 = (ImageView) findViewById(R.id.title_img2); img3 = (ImageView) findViewById(R.id.title_img3); } }<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="test.bwei.com.xiangmu.activity.MainActivity"> <test.bwei.com.xiangmu.view.TitleView android:layout_width="match_parent" android:layout_height="50dp" android:id="@+id/myTitle"></test.bwei.com.xiangmu.view.TitleView> </RelativeLayout>public class MainActivity extends AppCompatActivity { TitleView titleView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); setTitle(); } private void initView(){ titleView = (TitleView) findViewById(R.id.myTitle); } private void setTitle(){ titleView.setLeftListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"哎哎哎",Toast.LENGTH_LONG).show(); } }); titleView.setRightListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"aaa",Toast.LENGTH_LONG).show(); } }); } }
自定义View
最新推荐文章于 2022-08-08 20:10:34 发布