我怎么可以重复使用方法列表视图? [英] How can I Reuse Methods for ListViews?

查看:129
本文介绍了我怎么可以重复使用方法列表视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ListAC ListActivity几种方法,我想重用,并想放在单独的类(如果可能的话?)。我将有几十个的ListView活动(ListActivities即:ListAD,ListTCDS,listSFAR,等等,等等),将这些方法的正是本次活动相同,但在光标databaseCursor唯一的变化调用(即对于每一个ListActivity表名)。我打算把这些类及相关转化为自己的包W / N的应用程序(即:com.myCompany.myApp.AC)此外,W / N这些活动需要有多个coursers在查询的ORDER BY(即:......'名单'ASC | DESC,......'标题'ASC | DESC等)。 B4光标被调用时,我有方法检查ExternalStorageState了。我得到了类,StorageStateChecker(见下文),从LeffelMania(日Thnx!)重用ExternalStorageState,我想用仍 - 尽管它不是在下面的code实现的。我决定倒退*重新考虑这个(我搞砸自己了 - LOL),并使其更容易为你们和女生读通了code

正如你所看到的,这将导致在设备上不必要的冗余和字节空间主要量。我需要挤在设备上的空间,对于可能的,因为这个应用程序将是唯一的唯一目的,这些设备的用户(如果该项目的推进 - LOL)。

所以,我需要一种方法通过调用这些方法通单独的类,如果在所有可能的方式,我写这些方法和我的适配器剪下来。任何帮助瓦特/建议,方法,怎么过的,和code将是非常美联社preciative和帮助我学习Java / Android的。日Thnx!

*这个职位是相关的,并且从这里继续和的这里

更新:已完成的类是低于修订后的块。日Thnx所有帮助过我,现在我得到一个更好的理解类和放大器;法用法。

ListAC活动:

 公共类ListAC扩展ListActivity {
/ **
 *  - 第一次创建活动时调用
 * ================================================= ==================
 * /
@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    的setContentView(R.layout.list_view2);

    activityTitle =(TextView中)findViewById(R.id.titleBarTitle);
    activityTitle.setText(顾问环行器);

    storageState();
    sea​​rchList();
    nextActivity();
}

/ **
 *  - 检查,看是否SD卡安装和放大器;加载默认列表顺序
 * ================================================= =====================
 ** /
私人无效storageState(){
    如果(android.os.Environment.getExternalStorageState()。等于(
            android.os.Environment.MEDIA_MOUNTED)){

        orderASC_Label(); //加载列表

    }否则,如果(android.os.Environment.getExternalStorageState()。等于(
            android.os.Environment.MEDIA_UNMOUNTED)){
        Alerts.sdCardMissing(本);
    }
}

/ **
 *  - 默认列表顺序(升序)
 * ================================================= ====================
 ** /
公共无效orderASC_Label(){
    光标databaseCursor = db.rawQuery(
            SELECT * FROM AC_list ORDER BY`label` ASC,NULL);

    Adapter_AC databaseListAdapter =新Adapter_AC(这一点,
            R.layout.list_item,databaseCursor,新的String [] {标签,
                    标题,说明,gotoURL},新的INT [] {
                    R.id.label,R.id.listTitle,R.id.caption,R.id.dummy});

    databaseListAdapter.notifyDataSetChanged();
    this.setListAdapter(databaseListAdapter);
}

/ **
 *  - 开始下一个活动
 * ================================================= ====================
 ** /
公共无效nextActivity(){

    最终的ListView LV = getListView();
    lv.setTextFilterEnabled(真正的);
    lv.setClickable(真正的);

    lv.setOnItemClickListener(新AdapterView.OnItemClickListener(){

        @覆盖
        公共无效onItemClick(适配器视图<>一种,视图V,INT POS,长I​​D){

            字符串URL =;
            TextView的电视=(TextView中)v.findViewById(R.id.dummy);
            URL =(字符串)tv.getTag();

            字符串LBL =;
            TextView的TV2 =(TextView中)v.findViewById(R.id.label);
            LBL =(字符串)tv2.getTag();

            意图I =新的意图(List_AC.this,DocView.class);
            i.putExtra(URL,网址);
            i.putExtra(标签,LBL);
            startActivity(ⅰ);
        }
    });
}

/ **
 *  - 当菜单键是presses调度
 * ================================================= ====================
 ** /
@覆盖
公共布尔的onkeydown(INT键code,KeyEvent的事件){
    如果(键code == KeyEvent.KEY code_MENU){
        意图I =新的意图(List_AC.this,DashBoard.class);
        startActivity(ⅰ);
    }
    返回super.onKeyDown(键code,事件);
}

/ **
 *  - 局部变量
 * ================================================= ====================
 ** /
受保护的TextView activityTitle;
布尔mExternalStorageAvailable = FALSE;
布尔mExternalStorageWriteable = FALSE;
字符串extStorageDirectory = Environment.getExternalStorageDirectory()
        的ToString();
文件DBFILE =新的文件(extStorageDirectory
        +/XXX/xxx/dB/xxx.db);
SQLiteDatabase DB = SQLiteDatabase.openOrCreateDatabase(DBFILE,NULL);

/ ** ======================= END ======================= ============= ** /
}
 

我的适配器(AdaperAC):

 公共类AdapterAC扩展SimpleCursorAdapter {


静态游标dataCursor;
私人LayoutInflater mInflater;

公共Adapter_AC(上下文的背景下,INT布局,光标dataCursor,
        的String []从,INT []键){
    超(背景下,布局,dataCursor,从,到);
    this.dataCursor = dataCursor;
    mInflater = LayoutInflater.from(上下文);
}

公共查看getView(INT位置,查看convertView,ViewGroup中父){

    ViewHolder持有人;

    如果(convertView == NULL){
        convertView = mInflater.inflate(R.layout.list_item,NULL);

        持有人=新ViewHolder();
        holder.text1 =(TextView中)convertView.findViewById(R.id.label);
        holder.text2 =(TextView中)convertView.findViewById(R.id.listTitle);
        holder.text3 =(TextView中)convertView.findViewById(R.id.caption);
        holder.text4 =(TextView中)convertView.findViewById(R.id.dummy);

        holder.text4.setVisibility(View.GONE);

        convertView.setTag(保持器);

    } 其他 {
        支架=(ViewHolder)convertView.getTag();
    }

    dataCursor.moveToPosition(位置);

    INT label_index = dataCursor.getColumnIndex(标签);
    字符串标签= dataCursor.getString(label_index);

    INT title_index = dataCursor.getColumnIndex(标题);
    字符串标题= dataCursor.getString(title_index);

    INT description_index = dataCursor.getColumnIndex(说明);
    字符串描述= dataCursor.getString(description_index);

    INT goto_index = dataCursor.getColumnIndex(gotoURL);
    字符串gotoURL = dataCursor.getString(goto_index);

    holder.text1.setText(标签);
    holder.text1.setTag(标签);
    holder.text2.setText(职称);
    holder.text3.setText(介绍);
    //holder.text4.setText(gotoURL);
    holder.text4.setTag(gotoURL);

    返回convertView;
}

静态类ViewHolder {
    TextView的文本1;
    TextView的文本2;
    TextView的文本3;
    TextView的文本4;
}

}
 

修改为:

 公共类QueryDisplay扩展ListActivity {

受保护的TextView activityTitle;

布尔mExternalStorageAvailable = FALSE;
布尔mExternalStorageWriteable = FALSE;

。字符串extStorageDirectory = Environment.getExternalStorageDirectory()的toString();
文件DBFILE =新的文件(extStorageDirectory +/myComp/myApp/dB/myApp.db);
SQLiteDatabase DB = SQLiteDatabase.openOrCreateDatabase(DBFILE,NULL);

私有静态最后弦乐QUERY_KEY =QUERY_KEY;

/ **
 *  - 第一次创建活动时调用
 * ================================================= ==================
 * /
@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.list_view2);

    捆绑额外= getIntent()getExtras()。

    串Q = NULL;
    如果(临时演员!= NULL){

        Q = extras.getString(QUERY_KEY);
        Log.i(标签,让群众演员+临时演员);
    }

    reloadQuery(q)的;
}

公共无效reloadQuery(串Q){

    Log.i(标签,reloadQuery);

    如果(Environment.getExternalStorageState()。等于(Environment.MEDIA_MOUNTED)){

        光标C = db.rawQuery(Q,空);
        setListAdapter(新QueryAdapter(这一点,C));
        db.close();

    }其他 {
        Alerts.sdCardMissing(本);
    }
}

私有类QueryAdapter扩展的CursorAdapter {

    公共QueryAdapter(上下文的背景下,光标C){
        超(背景下,C);
        LayoutInflater.from(上下文);
    }

    @覆盖
    公共无效bindView(视图V,上下文的背景下,光标C){

            INT tvLabel = c.getColumnIndexOrThrow(标签);
            字符串标签= c.getString(tvLabel);
            TextView的labelTxt =(TextView中)v.findViewById(R.id.label);

            如果(labelTxt!= NULL){
                labelTxt.setText((+标签+));
            }

            INT tvTitle = c.getColumnIndexOrThrow(标题);
            字符串标题= c.getString(tvTitle);
            TextView的titleTxt =(TextView中)v.findViewById(R.id.listTitle);

            如果(titleTxt!= NULL){
                titleTxt.setText(职称);
            }

            INT tvDescription = c.getColumnIndexOrThrow(说明);
            字符串描述= c.getString(tvDescription);
            TextView的descriptionTxt =(TextView中)v.findViewById(R.id.caption);

            如果(descriptionTxt!= NULL){
                descriptionTxt.setText(介绍);
            }

            INT tvGoto = c.getColumnIndexOrThrow(gotoURL);
            字符串gotoURL = c.getString(tvGoto);
            TextView的gotoTxt =(TextView中)v.findViewById(R.id.dummy);

            如果(gotoTxt!= NULL){
                gotoTxt.setText(gotoURL);
            }

            gotoTxt.setVisibility(View.GONE);
            v.setTag(tvGoto);
    }

    @覆盖
    公共查看NewView的(上下文的背景下,光标C,父母的ViewGroup){

        最终的视图V = LayoutInflater.from(上下文).inflate(R.layout.list_item,父母,假);
        返回伏;
    }
}
}
 

...以及如何调用和放大器;注入查询:

  OnClickListener myClickListener =新OnClickListener(){
    @覆盖
    公共无效的onClick(视图v){
        如果(V == myBtn){

            字符串queryKey =SELECT * FROM a_tablet ORDER BY`column` ASC;
            意图I =新的意图(CurrentClass.this,QueryDisplay.class);
            i.putExtra(QUERY_KEY,queryKey);
            startActivity(ⅰ);
            }
 

解决方案

好像你在做额外的工作,数额特别巨大只是给了一堆不同的查询选项,你的光标。

为什么不能有一个ListActivity,有一个CursorAdapter的,而简单地把查询的意图,当你要启动的活动?

我要工作在一个小code为例,张贴在这里的编辑,但你真的过想这看起来。所有你要做的是在一个ListView显示查询结果。唯一的改变是查询。重用一切。

code样品:<​​/ P>

 公共类QueryDisplay扩展ListActivity {

    @覆盖
    保护无效的onCreate(包savedInstanceState){

        捆绑额外= getIntent()getExtras()。

        如果(临时演员!= NULL)
            reloadQuery(extras.getString(QUERY_KEY));

    }

    私人无效reloadQuery(查询){
        //建立你的光标位置。
        setAdapter(新QueryAdapter(这一点,光标));
    }

    私有类QueryAdapter扩展的CursorAdapter {

        @覆盖
        公共无效bindView(查看视图,上下文的背景下,光标光标){
            //设置您的观点在这里
        }

        @覆盖
        公共查看NewView的(上下文的背景下,光标光标的ViewGroup父){
            //这里创建新视图
            最终的视图中查看= LayoutInflator.from(上下文).inflate(R.layout.your_query_list_item_layout,父母,假);
            返回查看;
        }
    }
}
 

这是字面上的code,你应该需要(加填充插件为您的自定义视图和建设光标)。当你需要更改查询,你只需要调用 reloadQuery(查询字符串)和你设置。

I have several methods in the ListAC ListActivity that I want to reuse and would like to put in separate classes (if possible??). I will be having dozens of ListView Activities (ListActivities ie: ListAD, ListTCDS, listSFAR, etc., etc.) that will call on these methods that are exactly the same in this activity but the only changes in the 'Cursor databaseCursor' (ie. The Table name for each ListActivity). I plan on putting these Classes and related into their own packages w/n the application (ie: com.myCompany.myApp.AC) Also, w/n these Activities there needs to be multiple coursers for the query's 'ORDER BY' (ie: " ...'list' ASC | DESC", "...'title' ASC | DESC", etc.). B4 the cursors are called, I have the method for checking the ExternalStorageState too. I was given the class, StorageStateChecker (see below) from LeffelMania (THNX!) for reusing ExternalStorageState and I would like to use that still - even though its not implemented in the code below. I decided to step backwards* to rethink this (I screwed myself up - LOL) and to make it easier for you guys and gals to read thru the code.

As you can see, this will cause a major amount of unnecessary redundancy and byte-space on the device. I need to squeeze every bit of space possible on the devices because this app will be the only sole purpose to the users of these devices (if the project moves forward - LOL).

So, I need a way to cut it down by calling on these methods thru separate classes, if at all possible with the way I wrote these methods and my adapters. Any help w/suggestions, methods, how too's, and code will be very appreciative and helpful to me learning Java/Android. Thnx!!

*This post is related and is continuing from HERE and HERE.

UPDATE: The completed class is below in the REVISED block. Thnx to all the helped me and now I am getting a better understanding of classes & method usage.

ListAC Activity:

public class ListAC extends ListActivity {
/**
 * -- Called when the activity is first created
 * ===================================================================
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.list_view2);

    activityTitle = (TextView) findViewById(R.id.titleBarTitle);
    activityTitle.setText("ADVISORY CIRCULATORS");

    storageState();
    searchList();
    nextActivity(); 
}

/**
 * -- Check to See if the SD Card is Mounted & Loads Default List Order
 * ======================================================================
 **/
private void storageState() {
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED)) {

        orderASC_Label();// Loads the list

    } else if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_UNMOUNTED)) {
        Alerts.sdCardMissing(this);
    }
}

/**
 * -- Default List Order (Ascending)
 * =====================================================================
 **/
public void orderASC_Label() {
    Cursor databaseCursor = db.rawQuery(
            "SELECT * FROM AC_list ORDER BY `label` ASC", null);

    Adapter_AC databaseListAdapter = new Adapter_AC(this,
            R.layout.list_item, databaseCursor, new String[] { "label",
                    "title", "description", "gotoURL" }, new int[] {
                    R.id.label, R.id.listTitle, R.id.caption, R.id.dummy });

    databaseListAdapter.notifyDataSetChanged();
    this.setListAdapter(databaseListAdapter);
}

/**
 * -- Starts the Next Activity
 * =====================================================================
 **/
public void nextActivity() {

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);
    lv.setClickable(true);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> a, View v, int pos, long id) {

            String url = "";
            TextView tv = (TextView) v.findViewById(R.id.dummy);
            url = (String) tv.getTag();

            String lbl = "";
            TextView tv2 = (TextView) v.findViewById(R.id.label);
            lbl = (String) tv2.getTag();

            Intent i = new Intent(List_AC.this, DocView.class);
            i.putExtra("url", url);
            i.putExtra("label", lbl);
            startActivity(i);
        }
    });
}

/**
 * -- Dispatched when the Menu-Key is presses
 * =====================================================================
 **/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        Intent i = new Intent(List_AC.this, DashBoard.class);
        startActivity(i);
    }
    return super.onKeyDown(keyCode, event);
}

/**
 * -- Local Variables
 * =====================================================================
 **/
protected TextView activityTitle;
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String extStorageDirectory = Environment.getExternalStorageDirectory()
        .toString();
File dbfile = new File(extStorageDirectory
        + "/XXX/xxx/dB/xxx.db");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);

/** ======================= END ==================================== **/
}

My Adapter (AdaperAC):

public class AdapterAC extends SimpleCursorAdapter {


static Cursor dataCursor;
private LayoutInflater mInflater;

public Adapter_AC(Context context, int layout, Cursor dataCursor,
        String[] from, int[] to) {
    super(context, layout, dataCursor, from, to);
    this.dataCursor = dataCursor;
    mInflater = LayoutInflater.from(context);
}

public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item, null);

        holder = new ViewHolder();
        holder.text1 = (TextView) convertView.findViewById(R.id.label);
        holder.text2 = (TextView) convertView.findViewById(R.id.listTitle);
        holder.text3 = (TextView) convertView.findViewById(R.id.caption);
        holder.text4 = (TextView) convertView.findViewById(R.id.dummy);

        holder.text4.setVisibility(View.GONE);

        convertView.setTag(holder);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    dataCursor.moveToPosition(position);

    int label_index = dataCursor.getColumnIndex("label");
    String label = dataCursor.getString(label_index);

    int title_index = dataCursor.getColumnIndex("title");
    String title = dataCursor.getString(title_index);

    int description_index = dataCursor.getColumnIndex("description");
    String description = dataCursor.getString(description_index);

    int goto_index = dataCursor.getColumnIndex("gotoURL");
    String gotoURL = dataCursor.getString(goto_index);

    holder.text1.setText(label);
    holder.text1.setTag(label);
    holder.text2.setText(title);
    holder.text3.setText(description);
    //holder.text4.setText(gotoURL);
    holder.text4.setTag(gotoURL);

    return convertView;
}

static class ViewHolder {
    TextView text1;
    TextView text2;
    TextView text3;
    TextView text4;
}

}

REVISED to:

public class QueryDisplay extends ListActivity {

protected TextView activityTitle;

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File dbfile = new File(extStorageDirectory + "/myComp/myApp/dB/myApp.db");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);

private static final String QUERY_KEY = "QUERY_KEY";

/**
 * -- Called when the activity is first created
 * ===================================================================
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_view2);

    Bundle extras = getIntent().getExtras();

    String q = null;
    if (extras != null) {

        q = extras.getString(QUERY_KEY);
        Log.i("tag", "getting extras" + extras);
    }

    reloadQuery(q);
}

public void reloadQuery(String q) {

    Log.i("tag", "reloadQuery");

    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

        Cursor c = db.rawQuery(q, null);
        setListAdapter(new QueryAdapter(this, c));
        db.close();

    }else {
        Alerts.sdCardMissing(this);
    }
}

private class QueryAdapter extends CursorAdapter {

    public QueryAdapter(Context context, Cursor c) {
        super(context, c);
        LayoutInflater.from(context);
    }

    @Override
    public void bindView(View v, Context context, Cursor c) {

            int tvLabel = c.getColumnIndexOrThrow("label");
            String label = c.getString(tvLabel);
            TextView labelTxt = (TextView) v.findViewById(R.id.label);

            if (labelTxt != null) {
                labelTxt.setText("(" + label + ")");
            }

            int tvTitle = c.getColumnIndexOrThrow("title");
            String title = c.getString(tvTitle);
            TextView titleTxt = (TextView) v.findViewById(R.id.listTitle);

            if (titleTxt != null) {
                titleTxt.setText(title);
            }

            int tvDescription = c.getColumnIndexOrThrow("description");
            String description = c.getString(tvDescription);
            TextView descriptionTxt = (TextView) v.findViewById(R.id.caption);

            if (descriptionTxt != null) {
                descriptionTxt.setText(description);
            }

            int tvGoto= c.getColumnIndexOrThrow("gotoURL");
            String gotoURL = c.getString(tvGoto);
            TextView gotoTxt = (TextView) v.findViewById(R.id.dummy);

            if (gotoTxt != null) {
                gotoTxt.setText(gotoURL);
            }

            gotoTxt.setVisibility(View.GONE);
            v.setTag(tvGoto);
    }

    @Override
    public View newView(Context context, Cursor c, ViewGroup parent) {

        final View v = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        return v;
    }
}
}

...and how to call & inject the query:

OnClickListener myClickListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (v == myBtn) {

            String queryKey = "SELECT * FROM a_tablet ORDER BY `column` ASC";
            Intent i = new Intent(CurrentClass.this,QueryDisplay.class);
            i.putExtra("QUERY_KEY", queryKey);
            startActivity(i);
            }

解决方案

It seems like you're doing an extraordinary amount of extra work just to give a bunch of different query options for your Cursor.

Why not have one ListActivity, with one CursorAdapter, and simply put the query in the Intent when you want to start the Activity?

I'll work on a small code example and post it here in an edit, but you're really over-thinking this it seems. All you're trying to do is display the results of a query in a ListView. The only thing that is changing is the query. Reuse everything else.

Code sample:

public class QueryDisplay extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Bundle extras = getIntent().getExtras();

        if (extras != null)
            reloadQuery(extras.getString(QUERY_KEY));

    }

    private void reloadQuery(query) {
        // Build your Cursor here.
        setAdapter(new QueryAdapter(this, cursor));
    }

    private class QueryAdapter extends CursorAdapter {

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Set up your view here
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // Create your new view here
            final View view = LayoutInflator.from(context).inflate(R.layout.your_query_list_item_layout, parent, false); 
            return view;
        }
    }
}

That's literally all the code you should need (plus the fill-ins for your custom Views and building the Cursor). Whenever you need to change the query, you just need to call reloadQuery(String query) and you're set.

这篇关于我怎么可以重复使用方法列表视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆