1. 程式人生 > >流式佈局+資料庫

流式佈局+資料庫

1.主佈局
/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=".MainActivity">
<com.bawei.wangyaxiao.yidizhou2.demo.MyTitle
android:id="@+id/Mytile"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”></com.bawei.wangyaxiao.yidizhou2.demo.MyTitle>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="搜尋歷史" />

    <TextView
        android:id="@+id/Delete_Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:text="刪除" />
</RelativeLayout>

<com.bawei.wangyaxiao.yidizhou2.demo.MyLiuShi
    android:id="@+id/lishi_Myliushi"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></com.bawei.wangyaxiao.yidizhou2.demo.MyLiuShi>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:text="熱門搜尋" />
<com.bawei.wangyaxiao.yidizhou2.demo.MyLiuShi
    android:id="@+id/Myliushi"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></com.bawei.wangyaxiao.yidizhou2.demo.MyLiuShi>

/LinearLayout>

2.MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private String[] data = {"流感", "咳嗽", "過敏", "發燒", "感冒", "溼疹", "便祕", "痔瘡", "協和", "鼻炎", "失眠", "痛風", "上火", "腳氣", "抑鬱症", "性慾", "乳腺增生", "頭暈", "腰痛"};

private List mList=new ArrayList<>();
private MyLiuShi myLiuShi;
private MyTitle mTitle;
private TextView delText;
private Uri uri;
private ContentResolver resolver;
private MyLiuShi lishiMyliushi;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    resolver = getContentResolver();
    uri = Uri.parse("content://com.bawei.wangyaxiao.yidizhou2.provider.provider.MyProvider/news");
    initData();
    initView();
}

//查詢方法
private List<String>   getSel(){
    List<String> mdata=new ArrayList<>();
    Cursor cursor = resolver.query(uri, null, null, null, null);
    while(cursor.moveToNext()){
        String name = cursor.getString(cursor.getColumnIndex("uname"));
        mdata.add(name);
    }
    //倒敘輸出
    List<String> mstring=new ArrayList<>();
    for (int j = mdata.size()-1; j >=0 ; j--) {
            mstring.add(mdata.get(j));
    }
    return mstring;
}

private void initView() {
    myLiuShi = findViewById(R.id.Myliushi);
    myLiuShi.setData(mList);

    //新增監聽
    mTitle = findViewById(R.id.Mytile);
    mTitle.getTex().setOnClickListener(this);
    //展示歷史資料
    lishiMyliushi = findViewById(R.id.lishi_Myliushi);
    List<String> list = getSel();
    lishiMyliushi.setData(list);
    //刪除監聽
    delText = findViewById(R.id.Delete_Text);
    delText.setOnClickListener(this);
}

private void initData() {
    for (int i = 0; i <data.length ; i++) {
        mList.add(data[i]);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.Add_text:
            String name = mTitle.getEdit().trim();
            Log.e("name","-----"+name);

            //新增資料庫
            ContentValues values=new ContentValues();
            values.put("uname",name);
            resolver.insert(uri,values);

            //新增後實時的重新整理
            lishiMyliushi.removeAllViews();
            List<String> list = getSel();
            lishiMyliushi.setData(list);
            Toast.makeText(this,"點選",Toast.LENGTH_SHORT).show();
            break;
        case R.id.Delete_Text:
            //刪除資料庫
            List<String> mdata = getSel();
            for (int i = 0; i < mdata.size(); i++) {
                resolver.delete(uri,"uname=?",new String[]{mdata.get(i)});
            }
            lishiMyliushi.removeAllViews();
          
            break;
    }

}

}

3.流式佈局 MyLiuShi

public class MyLiuShi extends LinearLayout {

private final int mWidthPixels;
private final int mHeightPixels;


public MyLiuShi(Context context,  AttributeSet attrs) {
    super(context, attrs);
    //用上下文物件獲取螢幕的寬
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    //寬和高
    mWidthPixels = metrics.widthPixels;
    mHeightPixels = metrics.heightPixels;
    //設定垂直居中
    setOrientation(VERTICAL);
}

public void setData(List<String> mlist){
    LinearLayout linearLayout = getLine();
    for (int i = 0; i <mlist.size() ; i++) {
        String temp = mlist.get(i);
        int numWidth=0;
        int childCount = linearLayout.getChildCount();
        for (int j = 0; j <childCount ; j++) {
            //
             TextView tv= (TextView) linearLayout.getChildAt(j);
            LayoutParams layoutParams=(LayoutParams) tv.getLayoutParams();
            //左邊距
            int leftMargin = layoutParams.leftMargin;
            //元件的寬和高
            tv.measure(getMeasuredWidth(),getMeasuredHeight());
            //這一行的寬
            numWidth+=leftMargin+tv.getMeasuredWidth()+tv.getPaddingLeft()+tv.getPaddingRight();
        }

        TextView text = getText();
        LayoutParams layoutParams=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin=2;
        layoutParams.leftMargin=10;
        text.setLayoutParams(layoutParams);
        text.setText(temp);
        text.measure(getMeasuredWidth(),getMeasuredHeight());
        //一個元件的寬度
        int textWidth=text.getMeasuredWidth()+text.getPaddingRight()+text.getPaddingLeft();

        //判斷
        if(textWidth>=mWidthPixels){
            String s = temp.substring(0, 4);
            text.setText(s+"...");
            text.measure(getMeasuredWidth(),getMeasuredHeight());
            textWidth=text.getMeasuredWidth();
        }

        if(mWidthPixels>=numWidth+textWidth){
            linearLayout.addView(text);
        }else{
            linearLayout=getLine();
            linearLayout.addView(text);
        }
    }
}

private LinearLayout getLine(){
    //這是測量一行 是new出來的
    LinearLayout linearLayout=new LinearLayout(getContext());
    LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
    linearLayout.setLayoutParams(params);
    //this 是本類物件
    this.addView(linearLayout);

    return linearLayout;
}

private TextView getText(){
    TextView textView =new TextView(getContext());
    textView.setTextColor(Color.BLACK);
    textView.setTextSize(20);

    //呼叫樣式
    textView.setBackgroundResource(R.drawable.text_style);
    textView.setPadding(10,10,10,10);

    return textView;
}

}

4.text_style
</shape xmlns:android=“http://schemas.android.com/apk/res/android”>
</stroke
android:color="#14deb5"
android:width=“1dp”/>
</corners
android:radius=“10dp”/>
/shape>

5.自定義頭部佈局 title
</LinearLayout
xmlns:android=“http://schemas.android.com/apk/res/android
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“horizontal”>
</EditText
android:id="@+id/Edit_Text1"
android:layout_width=“0dp”
android:layout_weight=“6”
android:layout_height=“wrap_content”
android:drawableLeft="@mipmap/aaa"
android:drawablePadding=“5dp”
android:hint=“搜尋” />
</TextView
android:id="@+id/Add_text"
android:layout_width=“0dp”
android:layout_height=“wrap_content”
android:layout_weight=“1”
android:gravity=“center”
android:textSize=“20sp”
android:text=“新增” />

/LinearLayout>

6.方法 MyTitle
public class MyTitle extends LinearLayout {

private final EditText editText;
private final TextView addtext;

public MyTitle(Context context, AttributeSet attrs) {
    super(context, attrs);
    LayoutInflater.from(context).inflate(R.layout.title,this);

    editText = findViewById(R.id.Edit_Text1);
    addtext = findViewById(R.id.Add_text);
}

public String getEdit(){
    return editText.getText().toString();
}

public TextView getTex(){
    return addtext;
}

}

7.MyHelper
public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context) {
super(context, “yizhoumoni2”, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table if not exists news(uid integer primary key autoincrement,uname text)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

8.MyProvider

public class MyProvider extends ContentProvider {

private SQLiteDatabase db;

@Override
public boolean onCreate() {
    MyHelper helper=new MyHelper(getContext());
    db = helper.getWritableDatabase();
    return false;
}

@Override
public Cursor query(Uri uri,  String[] projection,  String selection,  String[] selectionArgs,  String sortOrder) {
    Cursor cursor = db.query("news", null, null, null, null,null,null);
    return cursor;
}

@Override
public String getType(Uri uri) {
    return null;
}

@Override
public Uri insert( Uri uri, ContentValues values) {
    db.insert("news",null,values);

    return null;
}

@Override
public int delete(Uri uri, String selection,  String[] selectionArgs) {
    db.delete("news",selection,selectionArgs);
    return 0;
}

@Override
public int update( Uri uri, ContentValues values,  String selection,  String[] selectionArgs) {
    return 0;
}

}