android自定义组件添加及界面刷新

来源:互联网 发布:下载电子琴简谱软件 编辑:程序博客网 时间:2024/04/29 11:52

自定义界面按钮有无

1.界面布局:使用网格布局,事先定义按钮,并设置在布局中的位置(适合少量按钮组件自定义情况,手法非正规)(由后台获取添加按钮情况,依照该数据添加到GradView里)

<?xml version="1.0" encoding="utf-8"?><ScrollView    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:scrollbars="vertical"    android:fadingEdge="vertical"    android:background="@drawable/gray"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/root"    >    <LinearLayout        android:orientation="vertical"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:weightSum="1"        >        <ImageView            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:src="@drawable/bs03"            android:adjustViewBounds="true"            android:maxWidth="500dip"            android:maxHeight="500dip"            />        <!--动态生成部分-->        <!--将其改为网格布局-->        <GridLayout            android:paddingTop="25dip"            android:paddingLeft="21dip"            android:id="@+id/gridLayout1"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:rowCount="4"            android:columnCount="2"            >            <ImageButton                android:id="@+id/nsrfx"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:src="@drawable/nsrfx2"                android:layout_columnSpan="1"/>                <ImageButton                    android:id="@+id/ssfx"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:src="@drawable/ssfx2"                    android:layout_columnSpan="1"/>                <ImageButton                    android:id="@+id/szrdfx"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:src="@drawable/szrdfx2"                    android:layout_columnSpan="1"                    />            <ImageButton                    android:id="@+id/tj"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:src="@drawable/tj2"                    android:layout_columnSpan="1" 
                   />
            <!--之前使用的表格布局--> 
<!-- <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:paddingTop="20dip"> <ImageButton android:id="@+id/jmskfx" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/jmskfx2" /> <ImageButton android:id="@+id/qsskfx" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/qsskfx2" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:paddingTop="20dip"> <ImageButton android:id="@+id/nsrjbxx" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/nsrjbxx2" /> </TableRow> --> </GridLayout> <!--动态生成部分结束--> </LinearLayout></LinearLayout></ScrollView>


2.java后台请求添加情况:(绿色为请求服务器部分,粉色为得到返回数据后添加按钮、及所有按钮及其位置定义,棕色为刷新更改后的主界面)

(之前采取的办法为添加activity传值给主activity,更改为向服务器求值,更简洁代码更少,以流量换复杂度**********访问失败情况需考虑bug)

package com.example.administrator.bs01;import android.app.AlertDialog;import android.content.Intent;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.view.MenuItem;import android.widget.GridLayout;import android.widget.ImageButton;import android.widget.TableLayout;import android.widget.TableRow;import android.widget.Button;import com.example.administrator.bs01.domain.User;import com.example.administrator.bs01.util.DialogUtil;import com.example.administrator.bs01.util.HttpUtil;import org.json.JSONObject;import java.util.HashMap;import java.util.Map;public class MainActivity extends ActionBarActivity {    ImageButton nsrfx,ssfx,szrdfx,tj,jmskfx,qsskfx,nsrjbxx,button1;    GridLayout gridLayout1;    int function;    String username = null;    int x1=2,x2=2,x3=3,y1=0,y2=1,y3=0;    //设置网格布局中各个按钮的位置    GridLayout.Spec rowSpec1=GridLayout.spec(x1);    GridLayout.Spec columnSpec1=GridLayout.spec(y1);    GridLayout.LayoutParams BT1 = new GridLayout.LayoutParams(rowSpec1,columnSpec1);//即第三行第一列    //        gridLayout1.addView(nsrjbxx,BT1);    GridLayout.Spec rowSpec2=GridLayout.spec(x2);    GridLayout.Spec columnSpec2=GridLayout.spec(y2);    GridLayout.LayoutParams BT2 = new GridLayout.LayoutParams(rowSpec2,columnSpec2);    GridLayout.Spec rowSpec3=GridLayout.spec(x3);    GridLayout.Spec columnSpec3=GridLayout.spec(y3);    GridLayout.LayoutParams BT3 = new GridLayout.LayoutParams(rowSpec3,columnSpec3);    /**     * 刷新, 这种刷新方法,只有一个Activity实例。     */    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Intent intent = getIntent();        //获取由Intent传递的Bundle携带内容        User u=(User) intent.getSerializableExtra("user");        username = u.getUsername();        initView();    }    /**     * 初始化页面元素     */    private void initView(){        nsrfx=(ImageButton)findViewById(R.id.nsrfx);        ssfx=(ImageButton)findViewById(R.id.ssfx);        szrdfx=(ImageButton)findViewById(R.id.szrdfx);        tj=(ImageButton)findViewById(R.id.tj);        gridLayout1=(GridLayout)findViewById(R.id.gridLayout1);        nsrjbxx=new ImageButton(this);        qsskfx=new ImageButton(this);        jmskfx=new ImageButton(this);        function = query(username);        addButton(function);        //提示窗//        String str="mmmmmm"+function;//        new AlertDialog.Builder(MainActivity.this).setTitle("????").setMessage(str).show();        tj.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Bundle data = new Bundle();                data.putSerializable("username", username);                //转到添加部分                Intent intent = new Intent(MainActivity.this, tjActivity.class);                intent.putExtras(data);                startActivity(intent);//                startActivityForResult(intent, 0);            }        });        nsrfx.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //转到纳税人分析                Intent intent=new Intent(MainActivity.this,nsrfxActivity.class);                startActivity(intent);            }        });        ssfx.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //转到税收分析                Intent intent = new Intent(MainActivity.this, ssfxActivity.class);                startActivity(intent);            }        });        szrdfx.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //转到税种认定分析                Intent intent=new Intent(MainActivity.this,szrdfxActivity.class);                startActivity(intent);            }        });        nsrjbxx.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //转到纳税人基本信息                Intent intent=new Intent(MainActivity.this,nsrjbxxActivity.class);                startActivity(intent);            }        });        jmskfx.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //转到减免税款分析                Intent intent=new Intent(MainActivity.this,jmskfxActivity.class);                startActivity(intent);            }        });        qsskfx.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //转到欠税税款分析                Intent intent=new Intent(MainActivity.this,qsskfxActivity.class);                startActivity(intent);            }        });    }    /**     * 调用onCreate(), 目的是刷新数据,     * 从另一activity界面返回到该activity界面时, 此方法自动调用     */    @Override    protected void onResume() {        super.onResume();        initView();//根据得到的添加情况刷新主界面                     
    }    //请求服务器传回function情况    private int query(String username) {        int function = 1000;        try        {            //建立Map映射,存储传递信息            Map<String,String> map = new HashMap<String,String>();            map.put("username", username);            // 设置访问的URL            String url = HttpUtil.BASE_URL+ "getFunction.jsp";            // 封装为json格式            JSONObject jsonObject = new JSONObject(HttpUtil.postRequest(url, map));            //将传回的值赋给function            function = jsonObject.getInt("function");        }        catch (Exception e)        {            DialogUtil.showDialog(this                    , "连接服务器异常,请稍后再试", false);            e.printStackTrace();        }        return function;    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }    /**     *重写onActivityResult()获取tjActivity回传值     */    @Override    protected void onActivityResult(int requestCode, int resultCode,                                    Intent intent) {        // ??requestCode??resultCode??        if (requestCode == 0 && resultCode == 0) {            Bundle bundleData = intent.getExtras();//            function = function + bundleData.getInt("function");            function = bundleData.getInt("function");            addButton(function);        }    }    public void addButton(int i){        int function1000 = i;        //显示此时function情况//        String str="mmmmmm"+function1000;//        new AlertDialog.Builder(MainActivity.this).setTitle("????").setMessage(str).show();        //bug1.布局无法灵活变动        //bug2.重复添加会崩溃        if(function1000<0){        }else{            if(function1000==1100){                nsrjbxx.setImageResource(R.drawable.nsrjbxx2);//                TableRow1.addView(nsrjbxx, BT1);//                TableLayout1.addView(TableRow1, TR1);                gridLayout1.addView(nsrjbxx,BT1);            }else if(function1000==1010) {                jmskfx.setImageResource(R.drawable.jmskfx2);//                TableRow2.addView(jmskfx, BT2);//                TableLayout1.addView(TableRow2, TR2);                gridLayout1.addView(jmskfx,BT1);            }else if(function1000==1001){                qsskfx.setImageResource(R.drawable.qsskfx2);//                TableRow3.addView(qsskfx, BT3);//                TableLayout1.addView(TableRow3, TR3);                gridLayout1.addView(qsskfx,BT1);            }else if(function1000==1110) {//                y2++;                nsrjbxx.setImageResource(R.drawable.nsrjbxx2);//                TableRow1.addView(nsrjbxx, BT1);//                TableLayout1.addView(TableRow1, TR1);                gridLayout1.addView(nsrjbxx,BT1);                jmskfx.setImageResource(R.drawable.jmskfx2);//                TableRow2.addView(jmskfx, BT2);//                TableLayout1.addView(TableRow2, TR2);                gridLayout1.addView(jmskfx,BT2);            }else if(function1000==1101) {//                y3++;;                nsrjbxx.setImageResource(R.drawable.nsrjbxx2);//                TableRow1.addView(nsrjbxx, BT1);//                TableLayout1.addView(TableRow1, TR1);                gridLayout1.addView(nsrjbxx,BT1);                qsskfx.setImageResource(R.drawable.qsskfx2);//                TableRow3.addView(qsskfx, BT3);//                TableLayout1.addView(TableRow3, TR3);                gridLayout1.addView(qsskfx,BT2);            }else if(function1000==1011) {//                y3++;                jmskfx.setImageResource(R.drawable.jmskfx2);//                TableRow2.addView(jmskfx, BT2);//                TableLayout1.addView(TableRow2, TR2);                gridLayout1.addView(jmskfx,BT1);                qsskfx.setImageResource(R.drawable.qsskfx2);//                TableRow3.addView(qsskfx, BT3);//                TableLayout1.addView(TableRow3, TR3);                gridLayout1.addView(qsskfx,BT2);            }else if(function1000==1111) {//                y2++;x3++;                nsrjbxx.setImageResource(R.drawable.nsrjbxx2);//                TableRow1.addView(nsrjbxx, BT1);//                TableLayout1.addView(TableRow1, TR1);                gridLayout1.addView(nsrjbxx,BT1);                jmskfx.setImageResource(R.drawable.jmskfx2);//                TableRow2.addView(jmskfx, BT2);//                TableLayout1.addView(TableRow2, TR2);                gridLayout1.addView(jmskfx,BT2);                qsskfx.setImageResource(R.drawable.qsskfx2);//                TableRow3.addView(qsskfx, BT3);//                TableLayout1.addView(TableRow3, TR3);                gridLayout1.addView(qsskfx,BT3);            }        }    }}
(3.关于刷新亦有其他方法比如:

如上所提http://blog.csdn.net/cryhelyxx/article/details/24502025

下拉刷新(可能此处不太合适)http://www.open-open.com/lib/view/open1430797271054.html)

4.添加部分的java后台:

package com.example.administrator.bs01;import android.app.AlertDialog;import android.content.Intent;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.View;import android.widget.TextView;import android.widget.Button;import android.widget.CheckBox;import android.widget.LinearLayout;import android.view.Menu;import android.view.MenuItem;import com.example.administrator.bs01.util.DialogUtil;import com.example.administrator.bs01.util.HttpUtil;import org.json.JSONObject;import org.w3c.dom.Text;import java.lang.ref.SoftReference;import java.util.HashMap;import java.util.Map;public class tjActivity extends ActionBarActivity {    Button buttontj;    CheckBox checkbox1,checkbox2,checkbox3;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_tj);        buttontj = (Button) findViewById(R.id.buttontj);        checkbox1 = (CheckBox) findViewById(R.id.cb1);        checkbox2 = (CheckBox) findViewById(R.id.cb2);        checkbox3 = (CheckBox) findViewById(R.id.cb3);//        final Button buttontest = new Button(this);        buttontj.setOnClickListener(                new View.OnClickListener() {                    @Override                    public void onClick(View v) {//                Intent intent=new Intent(tjActivity.this,MainActivity.class);//                startActivity(intent);//                Button.setVisibility(View.INVISIBLE) ;//原先采用的隐藏策略                        String str = "";                        String str0 = "某组件已在界面内";                        int had = -10000;                        int function = 1000;//                        if (checkbox1.isChecked()) {                            str += "纳税人基本信息";                            function += 100;                        }                        if (checkbox2.isChecked()) {                            str += "减免税款分析";                            function += 10;                        }                        if (checkbox3.isChecked()) {                            str += "欠税税款分析";                            function += 1;                        }                        //获得用户名                        Intent intent = getIntent();                        String username = (String) intent.getSerializableExtra("username");                        //返回的功能添加情况重复则不添加,不重复则添加                        boolean result = queryAdd(username, function);                        Bundle data = new Bundle();                        if(function == 1000){                            function = had;                        }                        else if (result) {                            new AlertDialog.Builder(tjActivity.this).setTitle("添加").setMessage(str0).show();                            function = had;                        } else {                            new AlertDialog.Builder(tjActivity.this).setTitle("添加").setMessage(str).show();//                          .setPositiveButton("ȷ��",null)                        }                        data.putInt("function", function);                        intent.putExtras(data);                        tjActivity.this.setResult(0, intent);                        new Thread() {                            @Override                            public void run() {                                super.run();                                try {                                    Thread.sleep(1000);//线程睡1秒                                } catch (InterruptedException e) {                                    e.printStackTrace();                                }                                /**                                 * Ҫִ�еIJ���                                 */                                tjActivity.this.finish();                            }                        }.start();                    }                }        );    }    private boolean queryAdd(String username,int function)    {        boolean result = true;        try        {            //添加Map映射            Map<String,String> map = new HashMap<String,String>();            map.put("username", username);            map.put("function", function+"");            // 设置URL            String url = HttpUtil.BASE_URL+ "addFunction.jsp";            // 封装为json对象            JSONObject jsonObject = new JSONObject(HttpUtil.postRequest(url, map));            //获取传回的result            result=jsonObject.getBoolean("result");            //提示窗口//            String str="kkkkkkkk"+function;//            new AlertDialog.Builder(Login.this).setTitle("test").setMessage(str).show();        }        catch (Exception e)        {            DialogUtil.showDialog(this                    , "连接服务器异常,请稍后再试", false);            e.printStackTrace();        }        return result;    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_tj, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

5.添加界面布局:

<?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="vertical"    android:layout_marginTop="10dip">    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="61dip"        android:clickable="true"        android:background="@drawable/home_select_list_style">        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginLeft="5dip"            android:layout_centerVertical="true"            android:orientation="horizontal">            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/tv01"                android:textSize="18dip"                android:textColor="@android:color/secondary_text_light"                android:textStyle="bold"/>            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:gravity="right">                <CheckBox                    android:id="@+id/cb1"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="right"                    android:layout_alignParentRight="true"/>            </LinearLayout>        </LinearLayout>    </RelativeLayout>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="61dip"        android:clickable="true"        android:background="@drawable/home_select_list_style">        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginLeft="5dip"            android:layout_centerVertical="true"            android:orientation="horizontal">            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/tv02"                android:textSize="18dip"                android:textColor="@android:color/secondary_text_light"                android:textStyle="bold"/>            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:gravity="right">                <CheckBox                    android:id="@+id/cb2"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="right"                    android:layout_alignParentRight="true"/>            </LinearLayout>        </LinearLayout>    </RelativeLayout>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="61dip"        android:clickable="true"        android:background="@drawable/home_select_list_style">        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_marginLeft="5dip"            android:layout_centerVertical="true"            android:orientation="horizontal">            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/tv03"                android:textSize="18dip"                android:textColor="@android:color/secondary_text_light"                android:textStyle="bold"/>            <LinearLayout                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:gravity="right">                <CheckBox                    android:id="@+id/cb3"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_gravity="right"                    android:layout_alignParentRight="true"/>            </LinearLayout>        </LinearLayout>    </RelativeLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_horizontal"        android:paddingTop="240dip">        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/btntj"            android:id="@+id/buttontj" />    </LinearLayout></LinearLayout>


添加界面效果图:

(新手上路》》》》》》》》》》》》》》)

0 0