一 :首先創建一個佈局文件 寫搜索框佈局
<?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(); } }); }