一 :首先创建一个布局文件 写搜索框布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@drawable/serach_backgrund" android:layout_height="wrap_content"> <!--二维码图片--> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/search_icon2"/> <!--输入框--> <EditText android:id="@+id/content" android:background="@null" android:layout_width="0dp" android:layout_weight="1" android:layout_height="30dp" /> <!--机器人图标--> <ImageView android:layout_width="30dp" android:layout_height="30dp" android:src="@drawable/root"/> </LinearLayout> 二:在drawable 下的 Drawable resource file中创建一个文件
<?xml version="1.0" encoding="utf-8"?> <shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android"> <!--设置颜色--> <solid android:color="#ccc"/> <!--尺寸--> <size android:width="100dp" android:height="30dp"/> <!--圆角边框角度--> <corners android:radius="15dp"/> </shape>
三:创建一个类 继承父布局
public class MySerachView extends LinearLayout { private EditText ed_content; //直接new处理 public MySerachView(Context context) { this(context, null); } //在布局文件中可用 AttributeSet:属性集 public MySerachView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } //手动调用 public MySerachView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //初始化一些东西 View view = View.inflate(context, R.layout.layout_mysearchview, this); //找到控件 ed_content = view.findViewById(R.id.content); } //获取内容 public String getcontent() { return ed_content.getText().toString(); } }四:在 MainActivity的布局中写 把自定义的控件加载进来
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.bw.lenovo.zhoukao1.MainActivity"> <!-- 自定义搜索框的控件--> <com.bw.lenovo.zhoukao1.MySerachView android:id="@+id/myserarchview" android:layout_width="match_parent" android:layout_height="wrap_content"></com.bw.lenovo.zhoukao1.MySerachView> </LinearLayout>五:在MainActivity中进行 操作(获取输入框的内容)
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); //获取到组合控件输入框里面的内容 mySerachView = (MySerachView) findViewById(R.id.myserarchview); //获取到 TextView serach_s = (TextView) findViewById(R.id.serach); serach_s.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String content = mySerachView.getcontent(); Toast.makeText(MainActivity.this, content + "**********", Toast.LENGTH_SHORT).show(); } }); }